java mysql预处理,如何在Java中使用预处理语句进行select查询?

该博客讲述了在使用PreparedStatement进行SQL查询时遇到的MySQLSyntaxErrorException,作者分享了如何通过修改`executeQuery()`方法调用方式来避免将问号直接发送到数据库引发的错误,并建议使用预编译语句提高代码健壮性。
摘要由CSDN通过智能技术生成

I had tried several times using prepared statements but it returns SQL exception. here is my code:

public ArrayList name(String mobile, String password) {

ArrayList getdata = new ArrayList();

PreparedStatement stmt = null;

try {

String login = "select mobile, password from tbl_1 join tbl_2 on tbl_1.fk_id=2.Pk_ID where mobile=? and password=?";

String data = "select * from tbl_2 where password='" + password + "'";

PreparedStatement preparedStatement = conn.prepareStatement(login);

preparedStatement.setString(1, mobile);

preparedStatement.setString(1, password);

ResultSet rs = preparedStatement.executeQuery(login);

Statement stmts = (Statement) conn.createStatement();

if (rs.next()) {

System.out.println("Db inside RS");

ResultSet data = stmts.executeQuery(data);

while (data.next()) { /* looping through the resultset */

getdata.add(data.getString("name"));

getdata.add(data.getString("place"));

getdata.add(data.getString("age"));

getdata.add(data.getString("job"));

}

}

} catch (Exception e) {

System.out.println(e);

}

return getdata;

}

While running this, I got the following SQL exception:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? and password=?' at line 1.

Any suggestion to make this work?

any piece of code is appreciated.

解决方案

You need to use:

preparedStatement.executeQuery();

instead of

preparedStatement.executeQuery(login);

when you pass in a string to executeQuery() that query is executed literally and thus the ? is send to the database which then creates the error. By passing query string you are not execution the "cached" prepared statement for which you passed the values.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值