java - 为什么我无法使用 SQLITE 在数据库中插入新数据?

标签 java sqlite jdbc

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/

相关文章:

java - 具有 map 属性的 Parcelable 嵌套类会导致应用程序崩溃

iphone - 除了 Firefox 扩展之外,Mac 上还有其他好的 SQLite 图形管理工具吗?

r - 如何从 R 更新 HIVE 中的环境变量?

java.sql.SQLException : Listener refused the connection with the following error: ORA-12519, TNS:找不到合适的服务处理程序

java - 分析与检测 - Java

java - Firebase 身份验证 - 许多用户使用相同的凭据登录

java - 优化对象列表的fasterxml ObjectMapper

java - Android:是否应该以异步方式访问应用程序中的数据库?

从两个表作为父对象和子对象的Mysql查询

java - 如何将 NetBeans 连接到 MySQL 数据库?