将字符串插入JDBC SQLite数据库



我正在创建一个需要本地数据库的java应用程序。我使用的是带有JDBC的SQLite数据库。我是Java本地数据库和JDBC的新手。

从互联网上的教程中,我已经大致了解了我在做什么,但我不太清楚。我现在正试图创建一个方法,可以接受一个表名和一组字符串,并将它们添加到表中。

我有两个问题:

首先,该方法不接受表作为要传递的参数。我知道我可以为每个表创建一个方法,但这效率很低,如果可能的话,我希望一个方法适用于所有表。

其次,我不知道如何将字符串传递到表中,因为要发送到表中的数据在SQL语句中,无法识别Java字符串。

以下是迄今为止的方法:

public static void Insert(Table table, String id, String name, String age, String address, String salary) {
    Connection c = null;
    Statement stmt = null;
    try {
        Class.forName("org.sqlite.JDBC");
        c = DriverManager.getConnection("jdbc:sqlite:test.db");
        c.setAutoCommit(false);
        System.out.println("Opened database successfully");
        stmt = c.createStatement();
        String sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "
                + "VALUES (1, 'Paul', 32, 'California', 20000.00 );";
        //I want this to write the strings passed in by the method, and to the table passed in by the method
        stmt.executeUpdate(sql);
        stmt.close();
        c.commit();
        c.close();
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        System.exit(0);
    }
    System.out.println("Records created successfully");
}

使用Prepared语句而不是CreateStatement,如下所示:

PreparedStatement stmt = c.prepareStatement
      ("insert into COMPANY values(?,?,?,?,?)");
      stmt.setInt(1,1);
      stmt.setString(2,"Paul");
      stmt.setInt(3,32);
      stmt.setString(4, "California");
      stmt.setBigDecimal(5, 20000.00);
      stmt.executeUpdate();

您应该为要插入的每个表创建一个Prepared语句。或者,您可以使用Table作为参数动态构建插入字符串

String insert_string = "insert into" + Table + "values, etc, etc"

最新更新