更新时间:2023-12-02 09:42:28
只需使用 PreparedStatement
而不是 声明
。
Just use PreparedStatement
instead of Statement
.
即使用
String sql = "INSERT INTO tbl (col1, col2, col3) VALUES (?, ?, ?)";
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, col1);
preparedStatement.setString(2, col2);
preparedStatement.setString(3, col3);
preparedStatement.executeUpdate();
而不是
String sql = "INSERT INTO tbl (col1, col2, col3) VALUES ('" + col1 + "', '" + col2 + "', '" + col3 + "')";
statement = connection.createStatement();
statement.executeUpdate(sql);
PreparedStatement
还提供方便的setter方法其他类型,例如 setInt()
, setDate()
, setBinaryStream()
,等等。
The PreparedStatement
also offers convenient setter methods for other types, such as setInt()
, setDate()
, setBinaryStream()
, etcetera.
请注意,此问题与JSP无关。它与Java有关。在JSP类中编写原始Java代码也被视为糟糕的做法一>。***实践是创建一个独立的类,它在特定的表上执行所有数据库交互任务,也称为DAO(数据访问对象)类。然后,您可以在servlet类中导入/使用此DAO类。
Please note that this issue is unrelated to JSP. It's related to Java in general. Writing raw Java code in a JSP class is also considered a poor practice. Best practice is to create a standalone class which does all the DB interaction tasks on a particular table, which is also called a DAO (Data Access Object) class. You can then import/use this DAO class in a servlet class.