[英]Insert String into JDBC SQLite database
我正在創建一個需要本地數據庫的Java應用程序。 我正在使用帶有JDBC的SQLite數據庫。 我是Java本地數據庫和JDBC的新手。
從互聯網上的教程中,我幾乎可以算出我在做什么,但是對我來說還不是很清楚。 我現在正在嘗試創建一種方法,該方法可以采用表名和一組字符串並將其添加到表中。
我有2個問題:
首先,該方法不接受將表作為傳入的參數。我知道我可以為每個表創建一個方法,但這效率低下,如果可能,我希望為所有表使用一種方法。
其次,我無法弄清楚如何將字符串傳遞到表中,因為要發送到表的數據在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 Statement。 或者,您可以使用Table作為參數動態構建插入字符串
String insert_string = "insert into" + Table + "values, etc, etc"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.