public class SQLiteJDBCDriverConnection {
此 block 用于连接到 sqlite 数据库并创建包含三列的“warehouses”表。
public static Connection connect() {
Connection conn = null;
try {
// db parameters
String url = "jdbc:sqlite:chinook.db";
String sql = "CREATE TABLE IF NOT EXISTS warehouses (\n"
+ " id integer PRIMARY KEY,\n"
+ " name text NOT NULL,\n"
+ " capacity real\n"
+ ")";
// create a connection to the database
conn = DriverManager.getConnection(url);
//Create table
Statement state = conn.createStatement();
state.executeUpdate(sql);
System.out.println("Connection to SQLite has been established.");
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
return conn;
}
此 block 用于创建具有三个参数的对象,以插入三列的新记录。
public static void newItem(int id, String name, int capacity) {
Connection con = connect();
PreparedStatement state;
String sql = "INSERT INTO warehouses(id,name,capacity) VALUES(?,?,?)";
try {
state = con.prepareStatement(sql);
state.executeUpdate();
}catch(Exception e) {
}
}
该 block 执行 newItem 函数。
public static void main(String[] args) {
newItem(4009,"plywood",5000);
}
}
最佳答案
您没有为 SQL 查询设置参数。
state = con.prepareStatement(sql);
之后需要使用 state.setXXX(index, value);
state = con.prepareStatement(sql);
state.setInt(1, id);
state.setString(2, name);
state.setInt(3, capacity);
state.executeUpdate();
正如评论中提到的,您至少需要将日志记录添加到您的 catch
block 中。当不再需要时,应关闭connection 和preparedStatement 对象。
编辑
在您的connect
方法中,您在finally
block 中close连接对象并返回关闭连接。然后您尝试在 newItem()
方法中使用关闭连接。
关于java - 为什么我无法使用 SQLITE 在数据库中插入新数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53010463/