对JDBC基础(一)中的代码进行优化
之前代码sql中的参数都是写死了,如果想通过参数动态的改变要查询的条件,之前的代码就需要进行改进,使之解耦。这就叫sql注入。sql注入与之前主要的优化在获得语句执行这一过程,下面将这个过程分成两步:
一、写sql时,使用“?”作为占位符写代替实际的查询条件
String sql = "select * from user where user_name=? and password=?;";
二、使用PreparedStatement来获得需要执行的sql
PreparedStatement pstmt = conn.PreparedStatement(sql);
三、往占位符中设置以及获取参数
设置:
String:setString()
Int:setInt()
...
获取:
String:getString()
int:getInt()
...
在不确定get到的值得类型时,也可以使用统一的getObject()
根据注入参数的类型选择相应的方法,方法中有两个参数:
- 第一个参数是往sql中注入第几个参数(从1开始)
- 第二个参数是实际要传入的参数值
pstmt.setString(1, "xiaohong");
pstmt.setString(2, "4321xh");
四、完整代码
package my.test.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestLogin2 {
/**
* @param args
* 使用PreparedStatement对sql传参进行优化
* @throws SQLException
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// TODO Auto-generated method stub
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/myproj";
Connection conn = DriverManager.getConnection(url, "root", "root123");
String sql = "select * from user where user_name=? and password=?;";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "xiaohong");
pstmt.setString(2, "4321xh");
ResultSet rs = pstmt.executeQuery();//由于sql已经在preparedStatement中,这个地方不用再传sql参数进去了
while (rs.next()){
System.out.println(rs.getObject(1)+"的密码为:"+rs.getObject(2)+" 登陆成功!");//提取参数使用相应的get方法
}
rs.close();
pstmt.close();
conn.close();
}
}