1 回答

TA貢獻1804條經驗 獲得超2個贊
您必須使用PreparedStatement。此外,強烈建議在 Java-8 之后將數據庫連接視為AutoClosables。您可以閱讀try-with-resources 聲明以了解如何執行此操作。最后,不要使用Exception類來捕獲異常。捕獲大多數情況下您會遇到的那種異常,在您的情況下是SQLException.
以下是上述內容的完整示例:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
public class SQLiteSample {
private static final String URL = "jdbc:sqlite:data.db";
public static void main(String[] args) {
createDb();
createTable();
insertPerson("Thomas", 15);
insertPerson("Walter", 32);
}
private static void insertPerson(String name, int age) {
final String SQL = "INSERT INTO persons VALUES(?,?)";
try (Connection con = getConnection(); PreparedStatement ps = con.prepareStatement(SQL);) {
ps.setString(1, name); // First question mark will be replaced by name variable - String;
ps.setInt(2, age); // Second question mark will be replaced by name variable - Integer;
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void createTable() {
final String SQL = "CREATE TABLE IF NOT EXISTS persons (name TEXT, age INTEGER);";
// This SQL Query is not "dynamic". Columns are static, so no need to use
// PreparedStatement.
try (Connection con = getConnection(); Statement statement = con.createStatement();) {
statement.executeUpdate(SQL);
} catch (SQLException e) {
e.printStackTrace();
}
}
private static void createDb() {
try (Connection conn = getConnection()) {
if (conn != null) {
conn.getMetaData();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL);
}
}
添加回答
舉報