JDBC(二)-preparedStatement接口
sql注入
- 注入原理:利用现有应用程序,将(恶意的)SQL命令注入到后台数据库引擎执行的能力,它可以通过在Web表单中输入(恶意)SQL语句得到一个存在安全漏洞的网站上的数据库,而不是按照设计者意图去执行SQL语句。
防止SQL注入的方法
- 过滤用户输入的数据中是否包含非法字符;
- 分步校验!先使用用户名来查询用户,如果查找到了,再比较密码;
- 使用PreparedStatement接口。
PreparedStatement接口的使用
PreparedStatement接口是Statement的子接口,你可以使用该接口来替换Statement接口。
PreparedStatement接口(预编译的SQL语句)
优点:
- 提高了代码的可读性和可维护性
- 提高了安全性
- 提高了SQL语句执行的性能
使用
- 使用Connection对象的prepareStatement(String sql):即创建它时就让它与一条SQL语句绑定;
- 编写SQL语句时,如果存在参数,使用“?”作为数据占位符;
- 调用PreparedStatement的setXXX()系列方法为占位符设置值,索引从1开始;
- 调用executeUpdate()或executeQuery()方法,但要注意,调用没有参数的方法;
使用JDBC完成数据库的增删改查操作
增
public class TestAdd {
//添加--
public static void main(String[] args) {
Connection connection = null;
PreparedStatement smt = null;
try {
// 1.加载驱动
String className = "com.mysql.jdbc.Driver";
Class.forName(className);
// 2.获取Connection连接
String url = "jdbc:mysql://localhost:3306/myschool";
String user = "root";
String password = "123456";
connection = DriverManager.getConnection(url, user, password);
StringBuffer sql = new StringBuffer();
sql.append("INSERT INTO student(studentno,loginpwd,studentname,sex,gradeid,");
sql.append("phone,address,borndate,email,identitycard)");
sql.append("values(?,?,?,?,?,?,?,?,?,?)");
// 3.创建preparedStatement对象
smt = connection.prepareStatement(sql.toString());
// 4.设置参数
smt.setObject(1, 20000);
smt.setObject(2, "123");
smt.setObject(3, "测试数据");
smt.setObject(4, "男");
smt.setObject(5, "1");
smt.setObject(6, "13212345678");
smt.setObject(7, "123");
smt.setObject(8, "1997-09-07");
smt.setObject(9, "123@kgc.cn");
smt.setObject(10, "123");
// 返回受影响的行数
int row = smt.executeUpdate();
if (row == 1) {
System.out.println("保存成功");
} else {
System.out.println("保存失败");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 5.释放资源
try {
if (smt != null) {
smt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
删:关键代码
String sql ="delete from student where studentno= ?";
ps = connection.prepareStatement(sql);
ps.setObject(1, stuNo);
int row = ps.executeUpdate();
if(row==1){
connection.commit();
System.out.println("删除成功");
}else{
System.out.println("删除失败");
}
查、改:关键代码
String sql1 = "select loginpwd from student where studentno=?";//通过学号查询密码
String sql2 = "update student set loginpwd =? where studentno =? ";//通过学号修改密码
ps = connection.prepareStatement(sql1);
ps.setObject(1, stuNo);
ResultSet rs = ps.executeQuery();
if(rs!=null && rs.next() ){
String loginPwd = rs.getString("loginPwd");
if(loginPwd.equals(passWord)){
System.out.println("请输入新密码");
String newpass = input.next();
ps=connection.prepareStatement(sql2);
ps.setString(1, newpass);
ps.setString(2, stuNo);
if(ps.executeUpdate()==1){
System.out.println("修改成功");
}else{
System.out.println("更新失败");
}
}
}else{
System.out.println("您输入的账号不存在");
}