Jay*_*Jay 5 java jdbc prepared-statement
我怎样才能准备好这个呢?
Statement stmt = con.createStatement();
long lastid = getLastId(stmt);
// create a SQL query
String strQuery = "INSERT INTO studenten " +
" (id, naam, adres, postcode, plaats, geboren) " +
" VALUES (" + (lastid+1) + "," +
"'" + contact.getNaam() + "'," +
"'" + contact.getAdres() + "'," +
"'" + contact.getPostcode() + "'," +
"'" + contact.getPlaats() + "'," +
"{d '" + contact.getGeboren() + "'}" +
") ";
stmt.executeUpdate(strQuery);
stmt.close();
con.close();
Run Code Online (Sandbox Code Playgroud)
Bal*_*usC 13
您需要将带有问号的值替换?为占位符.
String sql = "INSERT INTO studenten (id, naam, adres, postcode, plaats, geboren)"
+ " VALUES (?, ?, ?, ?, ?, ?)";
Connection connection = null;
PreparedStatement statement = null;
try {
connection = database.getConnection();
statement = connection.prepareStatement(sql);
statement.setLong(lastId + 1); // Why don't you use an generated sequence? This is plain ugly and errorprone.
statement.setString(contact.getNaam());
statement.setString(contact.getAdres());
statement.setString(contact.getPostcode());
statement.setString(contact.getPlaats());
statement.setDate(new java.sql.Date(contact.getGeboren().getTime())); // Assuming it returns java.util.Date
statement.executeUpdate();
} finally {
// Always close in finally to prevent resource leaks.
if (statement != null) try { statement.close(); } catch (SQLException ignore) {}
if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8496 次 |
| 最近记录: |