jdbc查询,返回结果为 “b.usercode” 字符串,而不是真正的数据库中的值,这个?应该怎么传值,不让使用拼接sql,要用PreparedStatement注入
String sql = " select ? from User b";
try {
connection = DriverManager.getConnection(url, userName, pwd);
} catch (SQLException e1) {
e1.printStackTrace();
}
try {
ps = connection.prepareStatement(sql);
ps.setString(1, "b.usercode");
rs = ps.executeQuery();
while (rs.next()) {
String usercode = rs.getString("usercode");
System.out.println("用户为:" + usercode);
}
b.usercode 本来就是固定的,为啥不直接写在sql里面
b.usercode 这个是 查询字段 ,你的sql 要 是 where 条件进行查询
像这样:
String sql = " select b.* from User b where b.usercode = ? ";
你现在的写法会把b.usercode当做一个字符串返回。要不使用拼接的方式 ,要不使用replace替换的方式:
sql = sql.replace("?","b.usercode")
解决方案:
首先,不应该使用字符串拼接的方式来传值,因为这样容易引起SQL注入的风险。应该使用PreparedStatement注入的方式来进行查询。
假设需要查询一个用户的信息,用户的CODE为b.usercode,那么正确的查询语句应该这样写:
String sql = "SELECT * FROM userInfo WHERE usercode = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, "b.usercode");
ResultSet rs = ps.executeQuery();
其中,问号所在的位置就是要传入的值的位置,而不需要拼接字符串。使用setString
方法可以设置传入的参数。
完整的示例代码如下:
public class JdbcTest {
public static void main(String[] args) {
String jdbcUrl = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
String username = "root";
String password = "root";
Connection conn;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(jdbcUrl, username, password);
String sql = "SELECT * FROM userInfo WHERE usercode = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, "b.usercode");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("username"));
}
rs.close();
ps.close();
conn.close();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
参考资料: