PreparedStatement可以防止sql注入问题,效率更高
先进行预编译sql,将要设置的字段值使用占位符
本质:预编译会将传递进来的参数包裹成字符,而单引号会被转义字符转换为空内容,有效的防止sql注入的问题
CRUD--SELECT
String sql = "select * from users where id=?";
st = connection.prepareStatement(sql);//预编译语句
st.setInt(1,14);
ResultSet resultSet = st.executeQuery();
while (resultSet.next()){
System.out.println(resultSet.getString("name"));
System.out.println(resultSet.getString("password"));
System.out.println(resultSet.getString("email"));
System.out.println(resultSet.getString("birthday"));
}
CRUD--INSERT
String sql = "insert into users(`name`,`password`,`email`,`birthday`) value (?,?,?,?)";
st = connection.prepareStatement(sql);//预编译语句
st.setString(1,"王丽萍");//传递参数
st.setString(2,"wlp123");
st.setString(3,"[email protected]");
//获得时间戳 java.Date 再将时间戳转换为sql.Date下面的时间
pst.setDate(4,new Date(new java.util.Date().getTime()));
int i = st.executeUpdate();
CRUD--DELETE
String sql = "delete from users where id=?";
st = connection.prepareStatement(sql);//预编译语句
st.setInt(1, 8);//传递参数
int i = st.executeUpdate();
if (i > 0) {
System.out.println("删除成功");
CRUD--UPDATE
String sql = "update users set `name`=? ,`password` = ?where id=?";
st = connection.prepareStatement(sql);//预编译语句
st.setString(1,"李昂");
st.setString(2,"[email protected]");
st.setInt(3,6);
int i = st.executeUpdate();
模拟登录测试
String sql = "select * from `users` where `name`=? and `password`=?";
statement = connection.prepareStatement(sql);
statement.setString(1,username);
statement.setString(2,password);
resultSet = statement.executeQuery();
标签:总结,每日,resultSet,st,sql,println,password,setString
From: https://www.cnblogs.com/wangxinyuan1108/p/18207328