JDBC 将参数传递给 sql 查询
JDBC pass parameters to sql query
我有
employee(id, name, company, salary);
需要显示给定 id 的数据
public static void Connect(String conString, String username, String password, int id) throws SQLException{
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection(conString, username, password);
String query = "select * from employee where id = " + id + "" ;
ResultSet rs = null;
Statement stmt = null;
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
while(rs.next()){
String name = rs.getString("name");
String company = rs.getString("company");
int salary = rs.getInt("salary");
System.out.println("Name: " + name + "\tCompany: " + company + "\tSalary: " + salary);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
但是这里我们是直接传递id。我们如何像参数化查询一样传递它(比如我们如何在 PreparedStatement
期间传递 ?
)
在这种情况下,您的查询应该是
String query = "select * from employee where id = ?";
您需要创建 PreparedStatement 而不是 Statement
PreparedStatement preparedStatement = conn.prepareStatement(query);
然后将你的id设置为prepared statement
preparedStatment.setInt(1, id);
终于执行查询
resultSet = preparedStatement.executeQuery();
它很旧 post 但我仍然想添加我的答案。
我没有足够的声誉来评论@prasad 的回答,所以我添加了小的更正作为单独的回答。实际上,在 praparedStatement.executeQuery() 中传递查询会抛出 MySQLSyntaxErrorException,因为它仍然调用 Statement.executeQuery 而不是 PreparedStatement.executeQuery()。我怎么知道?我不得不花大量时间来解决这个问题。
所以使用PreparedStatement.executeQuery()代替PreparedStament.executeQuery(query).
我有
employee(id, name, company, salary);
需要显示给定 id 的数据
public static void Connect(String conString, String username, String password, int id) throws SQLException{
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection(conString, username, password);
String query = "select * from employee where id = " + id + "" ;
ResultSet rs = null;
Statement stmt = null;
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
while(rs.next()){
String name = rs.getString("name");
String company = rs.getString("company");
int salary = rs.getInt("salary");
System.out.println("Name: " + name + "\tCompany: " + company + "\tSalary: " + salary);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
但是这里我们是直接传递id。我们如何像参数化查询一样传递它(比如我们如何在 PreparedStatement
期间传递 ?
)
在这种情况下,您的查询应该是
String query = "select * from employee where id = ?";
您需要创建 PreparedStatement 而不是 Statement
PreparedStatement preparedStatement = conn.prepareStatement(query);
然后将你的id设置为prepared statement
preparedStatment.setInt(1, id);
终于执行查询
resultSet = preparedStatement.executeQuery();
它很旧 post 但我仍然想添加我的答案。
我没有足够的声誉来评论@prasad 的回答,所以我添加了小的更正作为单独的回答。实际上,在 praparedStatement.executeQuery() 中传递查询会抛出 MySQLSyntaxErrorException,因为它仍然调用 Statement.executeQuery 而不是 PreparedStatement.executeQuery()。我怎么知道?我不得不花大量时间来解决这个问题。
所以使用PreparedStatement.executeQuery()代替PreparedStament.executeQuery(query).