为什么我不能使用SQLITE在数据库中插入新数据?

时间:2018-10-26 14:01:36

标签: java sqlite jdbc

public class SQLiteJDBCDriverConnection {

此块用于连接sqlite数据库并创建具有三列的“仓库”表。

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;


}

此块用于创建具有三个参数的对象,以便为三列插入新记录。

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) {

}
}

此块执行newItem函数。

public static void main(String[] args) {
    newItem(4009,"plywood",5000);
}
}

1 个答案:

答案 0 :(得分:1)

您没有为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块中。连接和prepareStatement对象应该在不再需要时关闭。

编辑

在您的connect方法中,您在finally块中关闭连接对象并返回 closed 连接。然后尝试在newItem()方法中使用封闭连接。

相关问题