Can't connect to a SQLite database

2019-08-28 21:44发布

问题:

try {
con = DriverManager.getConnection("jdbc:sqlite:db/Freepark.sqlite");
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("error al buscar la base de datos");
}

I am trying to do my first queries on an SQL database but I am having problems connecting to it, I think the problem is the URL for sure, the project name is BaseTest and inside project folder I have a subfolder called DB and inside it it's Freepark.sqlite. When I run the project the println message appears so I know that the problem is the url. Things like class.forName and so are already done above this code sample.

回答1:

Why dont you try either putting in the name with the relative path \ like: db\Freepark.sqlite

or also try putting the full path of the sqlite file.

Also are you including before the statements to enable the driver for sqlite such as:

 Class.forName("SQLite.JDBCDriver").newInstance(); 

or

 Class.forName("org.sqlite.JDBC"); 


回答2:

use this example

import java.sql.*;

public class Test {

public static void main(String[] args) throws Exception {

Class.forName("org.sqlite.JDBC");

Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db");

Statement stat = conn.createStatement();

stat.executeUpdate("drop table if exists people;");

stat.executeUpdate("create table people (name, occupation);");

PreparedStatement prep = conn.prepareStatement(
  "insert into people values (?, ?);");

prep.setString(1, "Gandhi");
prep.setString(2, "politics");
prep.addBatch();
prep.setString(1, "Turing");
prep.setString(2, "computers");
prep.addBatch();
prep.setString(1, "Wittgenstein");
prep.setString(2, "smartypants");
prep.addBatch();

conn.setAutoCommit(false);
prep.executeBatch();
conn.setAutoCommit(true);

ResultSet rs = stat.executeQuery("select * from people;");
while (rs.next()) {
  System.out.println("name = " + rs.getString("name"));
  System.out.println("job = " + rs.getString("occupation"));
}
rs.close();
conn.close();

}

}