Reputation: 10802
I have a factory class which "builds" different database connectors using one and the same interface. I have no trouble with MySQL
and Postgre
, but I do get some troubles when I try to connect and run some queries against SQLite
database. So, this is the disorder I see:
SQL db = SQL_Factory.build("SQLite");
System.out.println("BEFORE CONNECT");
db.connect();
System.out.println("BEFORE SHOW");
List<String> tables = db.show_tables();
and inside connect()
method I have these debugging commands:
try{
cnx = DriverManager.getConnection("jdbc:sqlite:" + db_path);
System.out.println("CONNECTED");
}
....
As a result of running the code I expected to see this in the console:
BEFORE CONNECT
CONNECTED
BEFORE SHOW
However, what I see looks rather strange:
BEFORE CONNECT
BEFORE SHOW
CONNECTED
Indeed, I'm getting a lot of other errors, but it's quite obvious, that all of them result from this disorder - CONNECTED
status appears long after other commands that need this connection to be set. So, I wonder where this async behaviour may come from and how to repair it? Thanks!
EDIT
Well, on the official page I see extremely strange lines of code:
connection = DriverManager.getConnection("jdbc:sqlite:sample.db");
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // <- WTF?????????
statement.executeUpdate("drop table if exists person");
So, is it really necessary to set timeout?? It looks like rubbish.
Upvotes: 0
Views: 527
Reputation: 264
I created a quick-and-dirty test.
Db.java
class Db {
Connection conn;
public Db() {
try {
Class.forName("org.sqlite.JDBC");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
void connect(String dbPath) throws SQLException {
try {
conn = DriverManager.getConnection("jdbc:sqlite:" + dbPath);
}
finally {
}
}
void doStuff() throws SQLException {
Statement statement = null;
try {
statement = conn.createStatement();
// statement.setQueryTimeout(30);
statement.executeUpdate("drop table if exists person");
}
finally {
if (statement != null) {
statement.close();
}
}
}
void disconnect() throws SQLException {
try {
conn.close();
}
finally {
conn = null;
}
}
}
Main.java
class Main {
public static void main(String[] args) throws SQLException {
Db db = new Db();
System.out.println("b4 connect");
db.connect("justATest");
System.out.println("connected");
db.doStuff();
System.out.println("done some stuff, disconnecting....");
db.disconnect();
System.out.println("disconnected");
}
}
Using jdk 1.8 over windows7, maven 3.3 and sqlite 3.8.11.2, the console output is as follows
Unfortunately I have no means of carrying out tests on a different OS.
Upvotes: 1