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);
}
}
添加回答
举报
