I've created a derby Embedded Database in my eclipse project, and it runs well on eclipse, but when packing the project in Runnable jar file, it fails in connecting the database.
I've done something similar to this video
http://vinayakgarg.wordpress.com/2012/03/07/packaging-java-application-with-apache-derby-as-jar-executable-using-eclipse/
Here is my Communicate.java
import java.io.File;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Communicate {
private static final String dbURL = "jdbc:derby:imagesDB;create=true";
private static final String tableName = "imageDB";
private static Connection conn = null;
private static Statement stmt = null;
public void insert(String path, String hash, long FileSize,
String label_name) throws NoSuchAlgorithmException, Exception {
try {
stmt = conn.createStatement();
stmt.execute("insert into " + tableName + " values (\'" + path
+ "\'," + FileSize + ",\'" + hash + "\'" + ",\'"
+ label_name + "\')");
stmt.close();
} catch (SQLException sqlExcept) {
sqlExcept.printStackTrace();
}
}
public void createConnection() {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
// Get a connection
conn = DriverManager.getConnection(dbURL);
} catch (Exception except) {
except.printStackTrace();
}
}
public void createTable() throws SQLException {
Statement st = conn.createStatement();
st.execute("CREATE TABLE "
+ tableName
+ " (fullPath VARCHAR(512), fileSize INTEGER, md5 VARCHAR(512), label_name VARCHAR(100))");
}
public void indexTable() throws SQLException {
Statement st = conn.createStatement();
st.execute("CREATE INDEX imageDBIndex ON imageDB (fullPath, label_name)");
}
public void deleteTable() throws SQLException {
Statement st = conn.createStatement();
st.execute("drop table " + tableName);
}
public String searchBySizeAndMD(String file_path, long size, String hash)
throws SQLException {
StringBuilder sb = new StringBuilder();
Statement st = conn.createStatement();
ResultSet rs = st
.executeQuery("SELECT fullPath, label_name FROM (SELECT * FROM imageDB im WHERE im.fileSize = "
+ size + " ) as A WHERE A.md5 = " + "\'" + hash + "\'");
while (rs.next()) {
sb.append("Image: (" + rs.getString("fullPath")
+ ") is at label: (" + rs.getString("label_name") + ")\n");
}
return sb.toString();
}
public String searchByImageName(String fileName) throws SQLException {
StringBuilder sb = new StringBuilder();
Statement st = conn.createStatement();
ResultSet rs = st
.executeQuery("SELECT fullPath, label_name FROM imageDB im WHERE im.fullPath like \'%"
+ fileName + "%\'");
while (rs.next()) {
File out_path = new File(rs.getString("fullPath"));
if (!fileName.equals(out_path.getName())) continue;
sb.append("Image: (" + out_path.getPath()
+ ") is at label: (" + rs.getString("label_name") + ")\n");
}
return sb.toString();
}
public void deleteLabel(String label) throws SQLException {
Statement st = conn.createStatement();
st.execute("DELETE FROM " + tableName + " WHERE label_name = \'" + label + "\'");
}
}
Any help in this issue?
The database should be in the folder where you runs the jar. If it's not then check docs how to specify connectionURL. If the project exported to the runnable jar file specify dependent libraries not to be extracted just added as is to the jar or to the local lib folder. These libraries are derby.jar and derbytools.jar should be in the classpath or manifest classpath. Use the following code to test your
Communicate class.
import java.io.File;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Communicate {
private static final String dbURL = "jdbc:derby:imagesDB;create=true";
private static final String tableName = "imageDB";
private static Connection conn = null;
private static Statement stmt = null;
public void insert(String path, String hash, long FileSize,
String label_name) throws NoSuchAlgorithmException, Exception {
try {
stmt = conn.createStatement();
stmt.execute("insert into " + tableName + " values (\'" + path
+ "\'," + FileSize + ",\'" + hash + "\'" + ",\'"
+ label_name + "\')");
stmt.close();
System.out.println("Inserted into table "+ tableName+ " values (\'" + path
+ "\'," + FileSize + ",\'" + hash + "\'" + ",\'"
+ label_name + "\')");
} catch (SQLException sqlExcept) {
sqlExcept.printStackTrace();
}
}
public void loadDriver() {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
System.out.println("Loaded the appropriate driver");
} catch (Exception except) {
except.printStackTrace();
}
}
public void createConnection() {
try {
// Get a connection
conn = DriverManager.getConnection(dbURL);
System.out.println("Connected to and created database ");
} catch (Exception except) {
except.printStackTrace();
}
}
public void createTable() throws SQLException {
Statement st = conn.createStatement();
st.execute("CREATE TABLE "
+ tableName
+ " (fullPath VARCHAR(512), fileSize INTEGER, md5 VARCHAR(512), label_name VARCHAR(100))");
System.out.println("Created table "+ tableName);
}
public void indexTable() throws SQLException {
Statement st = conn.createStatement();
st.execute("CREATE INDEX imageDBIndex ON imageDB (fullPath, label_name)");
System.out.println("Created index "+ "imageDBIndex");
}
public void deleteTable() throws SQLException {
Statement st = conn.createStatement();
st.execute("drop table " + tableName);
System.out.println("Deleted table "+ tableName);
}
public String searchBySizeAndMD(String file_path, long size, String hash)
throws SQLException {
StringBuilder sb = new StringBuilder();
Statement st = conn.createStatement();
ResultSet rs = st
.executeQuery("SELECT fullPath, label_name FROM (SELECT * FROM imageDB im WHERE im.fileSize = "
+ size + " ) as A WHERE A.md5 = " + "\'" + hash + "\'");
while (rs.next()) {
sb.append("Image: (" + rs.getString("fullPath")
+ ") is at label: (" + rs.getString("label_name") + ")\n");
}
return sb.toString();
}
public String searchByImageName(String fileName) throws SQLException {
StringBuilder sb = new StringBuilder();
Statement st = conn.createStatement();
ResultSet rs = st
.executeQuery("SELECT fullPath, label_name FROM imageDB im WHERE im.fullPath like \'%"
+ fileName + "%\'");
while (rs.next()) {
File out_path = new File(rs.getString("fullPath"));
if (!fileName.equals(out_path.getName())) continue;
sb.append("Image: (" + out_path.getPath()
+ ") is at label: (" + rs.getString("label_name") + ")\n");
}
return sb.toString();
}
public void deleteLabel(String label) throws SQLException {
Statement st = conn.createStatement();
st.execute("DELETE FROM " + tableName + " WHERE label_name = \'" + label + "\'");
}
public static void main(String[] args)
{
Communicate c = new Communicate();
c.loadDriver();
try {
c.createConnection();
c.createTable();
c.indexTable();
c.insert("/some/path", "12323423", 45656567, "label name");
String s = c.searchBySizeAndMD("/some/path", 45656567, "12323423");
System.out.println("Search result: "+ s);
c.deleteTable();
conn.commit();
System.out.println("Committed the transaction");
//Shutdown embedded database
try
{
// the shutdown=true attribute shuts down Derby
DriverManager.getConnection("jdbc:derby:;shutdown=true");
}
catch (SQLException se)
{
if (( (se.getErrorCode() == 50000)
&& ("XJ015".equals(se.getSQLState()) ))) {
// we got the expected exception
System.out.println("Derby shut down normally");
} else {
System.err.println("Derby did not shut down normally");
System.err.println(" Message: " + se.getMessage());
}
}
} catch (Exception e) {
System.err.println(" Message: " + e.getMessage());
} finally {
// release all open resources to avoid unnecessary memory usage
//Connection
try {
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
System.err.println(" Message: " + e.getMessage());
}
}
System.out.println("Communicate finished");
}
}
This is the output:
Loaded the appropriate driver
Connected to and created database
Created table imageDB
Created index imageDBIndex
Inserted into table imageDB values ('/some/path',45656567,'12323423','label name')
Search result: Image: (/some/path) is at label: (label name)
Deleted table imageDB
Committed the transaction
Derby shut down normally
Communicate finished
Related
How can I only make my application execute the changes to a database at the end of the while cycle?
I have this rollback method but I only the changes to be made to the database at the end of it because of inconsistent data handling
I have tried to set auto commit to false but even though the exception was thrown at the second iteration of the while cycle, the changes were still in the database(until the point before the interruption, the tables after that didn't suffer changes).
Am I doing something wrong?
#Override
public void rollback(Database database) throws CustomChangeException {
JdbcConnection connection = (JdbcConnection) database.getConnection();
try {
connection.setAutoCommit(false);
ResultSet rs = getTables(connection);
//if the user chose to use a suffix
if (this.getSuffix() != null) {
while (rs.next()) {
String tableName = rs.getString(3);
if (tableName.endsWith(this.getSuffix())) {
if (!checkColumnsExists(connection, tableName, newName)) {
throw new CustomChangeException("The column " + newName + " doesn't exist in the table " + tableName + " anymore.Please fix this");
}
PreparedStatement s = connection.prepareStatement(getRollbackQuery(tableName));
s.executeUpdate();
logger.info("Column name reversed to " + this.getColumnName() + " in table" + tableName);
}
}
}
//if the user chose to use a regex
if (this.getRegex() != null) {
Pattern pattern = Pattern.compile(this.getRegex());
while (rs.next()) {
String tableName = rs.getString(3);
Matcher matcher = pattern.matcher(tableName);
boolean matches = matcher.matches();
if (matches) {
if (!checkColumnsExists(connection, tableName, newName)) {
logger.error("The column " + newName + " doesn't exist in the table " + tableName + " anymore.Please fix this");
throw new CustomChangeException();
}
PreparedStatement s = connection.prepareStatement(getRollbackQuery(tableName));
s.executeUpdate();
logger.info("Column name reversed to " + this.getColumnName() + " in table" + tableName);
}
}
}
connection.commit();
} catch (SQLException | DatabaseException | DifferentDataTypeException e) {
logger.error(e.getMessage());
throw new CustomChangeException();
}
}
I have programmed an Discord bot that uses MySQL all great on my PC but after uploading it to my Server it comes following error:
Thu Oct 25 02:04:23 CEST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
java.sql.SQLNonTransientConnectionException: Could not create connection to database server. Attempted reconnect 3 times. Giving up.
On "public" server's its function's normaly (db4free.net) only this message is showing:
Thu Oct 25 02:01:04 CEST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
My Code:
(It fail's on "public static void connect(JDA jda)")
package org.spielearena.core;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.TextChannel;
import org.spielearena.util.RandomString;
import org.spielearena.util.config;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Random;
public class mysql {
public static Connection con = null;
public static ArrayList<TextChannel> asyncChannel = new ArrayList<>();
public static void connect(JDA jda) {
try {
if (con == null) {
con = DriverManager.getConnection("jdbc:mysql://" + config.config.getString("config.mysql.server") + ":" + config.config.getString("config.mysql.port") + "/" + config.config.getString("config.mysql.database") + "?autoReconnect=true", config.config.getString("config.mysql.user"), config.config.getString("config.mysql.pass"));
PreparedStatement ps = con.prepareStatement("CREATE TABLE IF NOT EXISTS `" + config.config.getString("config.mysql.prefix") + "keys` ( `serverkey` VARCHAR(500), `serverid` VARCHAR(500), `channelid` VARCHAR(500), `async` VARCHAR(500)) ENGINE = InnoDB;");
ps.executeUpdate();
ps = con.prepareStatement("CREATE TABLE IF NOT EXISTS `" + config.config.getString("config.mysql.prefix") + "toDiscord` ( `serverkey` VARCHAR(500), `message` VARCHAR(5000)) ENGINE = InnoDB;");
ps.executeUpdate();
ps = con.prepareStatement("CREATE TABLE IF NOT EXISTS `" + config.config.getString("config.mysql.prefix") + "fromDiscord` ( `serverkey` VARCHAR(500), `message` VARCHAR(50000), `unixTime` VARCHAR(500)) ENGINE = InnoDB;");
ps.executeUpdate();
ResultSet rs = con.createStatement().executeQuery("SELECT * FROM " + config.config.getString("config.mysql.prefix") + "keys");
while (rs.next()) {
if (!existsGuildAndChannel(jda, rs.getString("serverid"), rs.getString("channelid"))) {
ps = con.prepareStatement("DELETE FROM " + config.config.getString("config.mysql.prefix") + "keys WHERE serverkey='" + rs.getString("serverkey") + "'");
ps.executeUpdate();
} else {
if (rs.getString("async").equalsIgnoreCase("yes")) {
asyncChannel.add(jda.getGuildById(rs.getString("serverid")).getTextChannelById(rs.getString("channelid")));
}
}
}
} else {
throw new Exception("Internal error #001");
}
} catch (Exception e) {
System.out.println("MySQL error: " + e);
}
}
public static boolean existsGuildAndChannel(JDA jda, String guild, String channel) {
try {
return jda.getGuildById(guild).getTextChannelById(channel).canTalk();
} catch (Exception e) {}
return false;
}
public static void disconnect() {
try {
if (con != null) {
con.close();
con = null;
} else {
throw new Exception("Internal error #001");
}
} catch (Exception e) {
System.out.println("MySQL error: " + e);
}
}
public static void sync(String message, TextChannel channel) {
try {
if (con != null) {
if (asyncChannel.contains(channel)) {
ResultSet rs = con.createStatement().executeQuery("SELECT * FROM " + config.config.getString("config.mysql.prefix") + "keys WHERE channelid='" + channel.getId() + "' AND serverid='" + channel.getGuild().getId() + "';");
while (rs.next()) {
PreparedStatement ps = con.prepareStatement("INSERT INTO " + config.config.getString("config.mysql.prefix") + "fromDiscord (serverkey, message, unixTime) VALUES ('" + rs.getString("serverkey") + "', '" + message + "', '" + Integer.toString(((int)(System.currentTimeMillis() / 1000L))) + "')");
ps.execute();
}
}
}
} catch (Exception e) {
System.out.println("MySQL error: " + e);
}
}
public static void sync(JDA jda) {
try {
if (con != null) {
ArrayList<TextChannel> asyncChannel1 = new ArrayList<>();
ResultSet rs2 = con.createStatement().executeQuery("SELECT * FROM " + config.config.getString("config.mysql.prefix") + "keys");
while (rs2.next()) {
if (!existsGuildAndChannel(jda, rs2.getString("serverid"), rs2.getString("channelid"))) {
PreparedStatement ps = con.prepareStatement("DELETE FROM " + config.config.getString("config.mysql.prefix") + "keys WHERE serverkey='" + rs2.getString("serverkey") + "'");
ps.executeUpdate();
} else {
if (rs2.getString("async").equalsIgnoreCase("yes")) {
asyncChannel1.add(jda.getGuildById(rs2.getString("serverid")).getTextChannelById(rs2.getString("channelid")));
}
}
}
asyncChannel = asyncChannel1;
ResultSet rs = con.createStatement().executeQuery("SELECT * FROM " + config.config.getString("config.mysql.prefix") + "toDiscord");
while (rs.next()) {
PreparedStatement ps = con.prepareStatement("DELETE FROM " + config.config.getString("config.mysql.prefix") + "toDiscord WHERE serverkey='" + rs.getString("serverkey") + "' AND message='" + rs.getString("message") + "'");
ps.execute();
ResultSet rs1 = con.createStatement().executeQuery("SELECT * FROM " + config.config.getString("config.mysql.prefix") + "keys WHERE serverkey='" + rs.getString("serverkey") + "'");
while (rs1.next()) {
if (!existsGuildAndChannel(jda, rs1.getString("serverid"), rs1.getString("channelid"))) {
ps = con.prepareStatement("DELETE FROM " + config.config.getString("config.mysql.prefix") + "keys WHERE serverkey='" + rs.getString("serverkey") + "'");
ps.executeUpdate();
} else {
jda.getGuildById(rs1.getString("serverid")).getTextChannelById(rs1.getString("channelid")).sendMessage(rs.getString("message")).queue();
}
}
}
} else {
throw new Exception("Internal error #001");
}
} catch (Exception e) {
System.out.println("MySQL error: " + e);
}
}
public static String generateKey(Guild guild, TextChannel channel, Boolean async) {
try {
if (con != null) {
String asy = "no";
if (async) {
asy = "yes";
asyncChannel.add(channel);
}
RandomString rnd = new RandomString(32, new Random());
String key = "";
boolean finish = false;
try {
ResultSet rs = con.createStatement().executeQuery("SELECT * FROM " + config.config.getString("config.mysql.prefix") + "keys WHERE serverid='" + guild.getId() + "'");
while (rs.next()) {
if (rs.getString("channelid").equalsIgnoreCase(channel.getId())) {
return rs.getString("serverkey");
}
}
} catch (Exception e) {
System.out.println("MySQL error: " + e);
}
while (!finish) {
key = rnd.nextString();
try {
boolean alredyExists = false;
ResultSet rs = con.createStatement().executeQuery("SELECT * FROM " + config.config.getString("config.mysql.prefix") + "keys WHERE serverkey='" + key + "'");
while (rs.next()) {
alredyExists = true;
}
if (!alredyExists) {
PreparedStatement ps = con.prepareStatement("INSERT INTO " + config.config.getString("config.mysql.prefix") + "keys (serverkey, serverid, channelid, async) VALUES ('" + key + "', '" + guild.getId() + "', '" + channel.getId() + "', '" + asy + "')");
ps.execute();
finish = true;
}
} catch (Exception e) {
System.out.println("MySQL error: " + e);
}
}
return key;
} else {
throw new Exception("Internal error #001");
}
} catch (Exception e) {
System.out.println("MySQL error: " + e);
}
return null;
}
}
My Server:
5.7.24 - MySQL Community Server (GPL)
Linux version 4.9.0-8-amd64 (debian-kernel#lists.debian.org) (gcc version 6.3.0 20170516 (Debian 6.3.0-18+deb9u1) ) #1 SMP Debian 4.9.110-3+deb9u6 (2018-10-08)
openjdk version "1.8.0_181"
OpenJDK Runtime Environment (build 1.8.0_181-8u181-b13-1~deb9u1-b13)
OpenJDK 64-Bit Server VM (build 25.181-b13, mixed mode)
The below java method sets the ResultSet data to a bean class and I am fetching the data. But, the method runHiveQuery() returns only one row that is the last record in the table. While debugging the code i found that the resultset is being looped twice as we have two records. But, while returning the bean class object there is some issue as it retrieves only one record.
Unable to find what is going wrong.
public CSPData getCSPData() throws SQLException {
try {
String drivername = "org.apache.hive.jdbc.HiveDriver";
Class.forName(drivername);
connection = DriverManager.getConnection("jdbc:hive2://hddev-c01-edge-01:20000/");
statement = connection.createStatement();
resultset = statement.executeQuery(
"select distinct db_name as db_name,db_server_name as db_server_name,lower(db_name) as l_db_name,lower(db_server_name) as l_server_name,regexp_replace(lower(db_server_name), '-', '_') as server_name,db_server_name_secondary as db_server_name_secondary from csp.curated_input");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (SQLException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
while (resultset.next()) {
cspdata.setDbName(resultset.getString("db_name"));
cspdata.setDbServerName(resultset.getString("db_server_name"));
cspdata.setDbServerNameSecondary(resultset.getString("db_server_name_secondary"));
cspdata.setlDbName(resultset.getString("l_db_name"));
cspdata.setlServerName(resultset.getString("l_server_name"));
cspdata.setServerName(resultset.getString("server_name"));
}
return cspdata;
}
public void runHiveQuery() throws SQLException {
CSPData cspdata = hivedao.getCSPData();
String hive_db = "csp";
String dbname = cspdata.getDbName();
String dbservername = cspdata.getDbServerName();
String servername = cspdata.getlServerName();
String drop = "Drop table if exists " + hive_db + "." + "IB_C3_" + dbname + "_" + dbservername;
String insert = "insert into table " + hive_db + "." + "IB_export_log select " + "\'ib_c3_" + dbname + "_"
+ servername + "\' from " + hive_db + "." + "dual limit 1";
System.out.println(drop);
System.out.println(insert);
}
Your code returns the last record since it only returns a single record. You should return a List :
public List<CSPData> getCSPData() throws SQLException {
List<CSPData> result = new ArrayList<>();
try {
String drivername = "org.apache.hive.jdbc.HiveDriver";
Class.forName(drivername);
connection = DriverManager.getConnection("jdbc:hive2://hddev-c01-edge-01:20000/");
statement = connection.createStatement();
resultset = statement.executeQuery(
"select distinct db_name as db_name,db_server_name as db_server_name,lower(db_name) as l_db_name,lower(db_server_name) as l_server_name,regexp_replace(lower(db_server_name), '-', '_') as server_name,db_server_name_secondary as db_server_name_secondary from csp.curated_input");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (SQLException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
while (resultset.next()) {
CSPData cspdata = new CSPData ();
cspdata.setDbName(resultset.getString("db_name"));
cspdata.setDbServerName(resultset.getString("db_server_name"));
cspdata.setDbServerNameSecondary(resultset.getString("db_server_name_secondary"));
cspdata.setlDbName(resultset.getString("l_db_name"));
cspdata.setlServerName(resultset.getString("l_server_name"));
cspdata.setServerName(resultset.getString("server_name"));
result.add(cspdata);
}
return result;
}
i need to create a table in access database. For this i tried with the following code
public class Testac {
public static void main(String[] args) {
try {
System.out.println("Begining conn");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String accessFileName = "Centre";
String connURL = "jdbc:odbc:;DRIVER=Microsoft Access Driver (*.accdb);DBQ=" + accessFileName + ".accdb;PWD=";
Connection con = DriverManager.getConnection(connURL, "", "");
Statement stmt = con.createStatement();
System.out.println("Conn done succesfully");
stmt.execute("create table student ( Name string, ID integer )"); // create a student
stmt.execute("insert into student values(‘Md. SHAHJALAL’, ‘02223540’)"); // insert data into student
stmt.execute("select * from student"); // execute query in table student
ResultSet rs = stmt.getResultSet(); // get any Resultt that came from our query
if (rs != null) {
while (rs.next()) {
System.out.println("Name: " + rs.getString("Name") + " ID: " + rs.getString("ID"));
}
}
stmt.close();
con.close();
} catch (Exception err) {
System.out.println("ERROR: " + err);
}
}
}
But it throws the following error " ERROR: java.sql.SQLException: [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified ".
It is possible with UCanAccess
con = ConnectMdb(homedirectory+"/"+"Centre.accdb");
if (con != null) {
Statement st3 = null;
try {
st3 = (Statement) con.createStatement();
} catch (SQLException ex) {
Logger.getLogger(DataEntryScreen.class.getName()).log(Level.SEVERE, null, ex);
}
String sqlq3 = "CREATE TABLE REGISTRATION " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";
// System.out.println(sqlq1);
// ResultSet rs3 = null;
try {
st3.execute(sqlq3);
} catch (SQLException ex) {
Logger.getLogger(DataEntryScreen.class.getName()).log(Level.SEVERE, null, ex);
}
Try this.
Below Corrected Code may help you:
mistake in connection string and while creating table. need to use executeUpdate method
public class Testac {
public static void main(String[] args) {
try {
System.out.println("Begining conn");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String accessFileName = "Centre";
String connURL = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + accessFileName + ".accdb;PWD=";
Connection con = DriverManager.getConnection(connURL, "", "");
Statement stmt = con.createStatement();
System.out.println("Conn done succesfully");
stmt.executeUpdate("create table student ( Name string, ID integer )"); // create a student
stmt.execute("insert into student values(‘Md. SHAHJALAL’, ‘02223540’)"); // insert data into student
stmt.execute("select * from student"); // execute query in table student
ResultSet rs = stmt.getResultSet(); // get any Resultt that came from our query
if (rs != null) {
while (rs.next()) {
System.out.println("Name: " + rs.getString("Name") + " ID: " + rs.getString("ID"));
}
}
stmt.close();
con.close();
} catch (Exception err) {
System.out.println("ERROR: " + err);
}
}
}
The problem is on this line:
String connURL = "jdbc:odbc:;DRIVER=Microsoft Access Driver (*.accdb);DBQ=" + accessFileName + ".accdb;PWD=";
which you should change to:
String connURL = "jdbc:odbc:DRIVER=Microsoft Access Driver (*.accdb);DBQ=" + accessFileName + ".accdb;PWD=";
i.e. you need to remove the semi-colon between jdbc and odbc.
I have this java function that runs and produces an error. I cannot figure out why this is occurring because this is the first function in the program to run so no other connections, statements, or result sets have been opened. The error is
Operation not allowed after ResultSet closed
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:768)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:7008)
at equipmentinventoryimporter.Importer.sqlTable(Importer.java:219)
at equipmentinventoryimporter.Importer.main(Importer.java:58)
and the function is
private static void sqlTable(SQLTableJob sqltableJob) {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connMySQL2 = null;
Statement stntMySQL2 = null;
try {
connMySQL2 = DriverManager.getConnection(mysqlAddress, mysqlUsername, mysqlPassword);
stntMySQL2 = connMySQL2.createStatement();
//MySQL Transaction
System.out.println("Starting " + sqltableJob.getMysqlTable() + " transaction");
stntMySQL2.execute("START TRANSACTION");
String insertQuery = "";
try {
final String inactiveQuery = "UPDATE `" + sqltableJob.getMysqlSchema() + "`.`" + sqltableJob.getMysqlTable() + "` SET `active`=0";
stntMySQL2.executeUpdate(inactiveQuery);
final ResultSet rs2 = stntMySQL2.executeQuery(sqltableJob.getSQLSelectQuery());
int counter = 0;
while (rs2.next()) {
counter++;
final String mysqlSetClause = sqltableJob.getMysqlSetClause(rs2);
insertQuery = "INSERT INTO `" + sqltableJob.getMysqlSchema() + "`.`" + sqltableJob.getMysqlTable() + "` SET " +
mysqlSetClause +
" ON DUPLICATE KEY UPDATE " +
mysqlSetClause;
stntMySQL2.executeUpdate(insertQuery);
if (counter % 5000 == 0) {
System.out.println("Processed " + counter + " rows.");
}
}
rs2.close();
if (!sqltableJob.isKeepInactives()) {
final String deleteQuery = "DELETE FROM `" + sqltableJob.getMysqlSchema() + "`.`" + sqltableJob.getMysqlTable() + "`" +
"WHERE `active`=0";
stntMySQL2.executeUpdate(deleteQuery);
}
stntMySQL2.execute("COMMIT");//last line of try block
System.out.println("Committed " + sqltableJob.getMysqlTable() + " transaction");
} catch (Exception ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
System.out.println("Transaction level exception thrown.");
System.out.println(insertQuery);
stntMySQL2.execute("ROLLBACK");
System.out.println("MySQL query rolled back.");
}
//Another MySQL Transaction goes here
} catch (Exception ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
System.out.println("Connection level exception thrown.");
} finally {
if (stntMySQL2 != null) {
try {
stntMySQL2.close();
} catch (Exception ex) {
}
}
if (connMySQL2 != null) {
try {
connMySQL2.close();
} catch (Exception ex) {
}
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
ex.printStackTrace();
System.out.println("Program level exception thrown.");
}
}
SQLTableJob is
package equipmentinventoryimporter;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
* #author jmgreen
*/
public interface SQLTableJob {
public String getMysqlSchema();
public String getMysqlTable();
public String getSQLSelectQuery();
public String getMysqlSetClause(ResultSet rs) throws SQLException;
public boolean isKeepInactives();
}
and the specific SQLTableJob being referenced is
public class SQLTableJob10I implements SQLTableJob{
public boolean isKeepInactives() {
return true;
}
public String getMysqlSchema() {
return "Temp_Equipment_Inventory";
}
public String getMysqlTable() {
return "PC_Combined";
}
public String getSQLSelectQuery() {
final String sqlSelectQuery = "SELECT *" +
" FROM Temp_Equipment_Inventory.PC_Table10i";
return sqlSelectQuery;
}
public String getMysqlSetClause(ResultSet rs) throws SQLException {
final String mysqlSetClause =
"`Account_No`=" + Importer.sqlChar(rs.getString("Account_No")) +
",`Inventory_No`=" + Importer.sqlChar(rs.getString("Inventory_No")) +
",`Building_No`=" + Importer.sqlChar(rs.getString("Building_No")) +
",`Location`=" + Importer.sqlChar(rs.getString("Location")) +
",`FYYR_No`=" + Importer.sqlChar(rs.getString("FYYR_No")) +
",`Cost`=" + Importer.sqlChar(rs.getString("Cost")) +
",`Name`=" + Importer.sqlChar(rs.getString("Name")) +
",`Desc1`= ''" +
",`Desc2`= ''" +
",`Desc3`= ''" +
",`CDCATY`=" + Importer.sqlChar(rs.getString("CDCATY")) +
",`CDSRCE`=" + Importer.sqlChar(rs.getString("CDSRCE")) +
",`FLDCAL`=" + Importer.sqlChar(rs.getString("FLDCAL")) +
",`CDACQN`=" + Importer.sqlChar(rs.getString("CDACQN")) +
",`FLOWNR`=" + Importer.sqlChar(rs.getString("FLOWNR")) +
",`FLSHAR`=" + Importer.sqlChar(rs.getString("FLSHAR")) +
",`CDDELT`=" + Importer.sqlChar(rs.getString("CDDELT")) +
",`CNYTDT`=" + Importer.sqlChar(rs.getString("CNYTDT")) +
",`NOPURO`=" + Importer.sqlChar(rs.getString("NOPURO")) +
",`NOPIMO`=" + Importer.sqlChar(rs.getString("NOPIMO")) +
",`CDPREI`=" + Importer.sqlChar(rs.getString("CDPREI")) +
",`Original_Amount`=" + Importer.sqlChar(rs.getString("Original_Amount")) +
",`Serial_Code`=" + Importer.sqlChar(rs.getString("Serial_Code")) +
",`CDCOMP`=" + Importer.sqlChar(rs.getString("CDCOMP")) +
",`NOCHECK`=" + Importer.sqlChar(rs.getString("NOCHECK")) +
",`CDCOMM`=" + Importer.sqlChar(rs.getString("CDCOMM")) +
",`Last_Update`=" + Importer.sqlDate(rs.getString("Last_Update")) +
",`CDDEPT`=" + Importer.sqlChar(rs.getString("CDDEPT")) +
",`Room_No`=" + Importer.sqlChar(rs.getString("Room_No")) +
",`Date_Scanned`=" + Importer.sqlDate(rs.getString("Date_Scanned")) +
",`Date_Acquired`=" + Importer.sqlDate(rs.getString("Date_Acquired")) +
",`Manufacturer_Name`=" + Importer.sqlChar(rs.getString("Manufacturer_Name")) +
",`Expiry_Date`=" + Importer.sqlDate(rs.getString("Expiry_Date")) +
",`Active`='1'";
return mysqlSetClause;
}
}
From the Javadoc:
A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.
From your code:
stntMySQL2.executeUpdate(inactiveQuery);
final ResultSet rs2 = stntMySQL2.executeQuery(sqltableJob.getSQLSelectQuery());
while (rs2.next()) {
...
stntMySQL2.executeUpdate(insertQuery);
You are re-executing stntMySQL2 inside the loop. This automatically closes rs2.
To fix, use a different statement object inside the loop.