正是前面一篇的SQL注入问题,我们学习到了使用PreparedStatement对象代替Statement来解决这个问题,所以,从这篇开始,我们就要抛弃Statement对象,以后都使用PreparedStatement对象,所以,这篇就使用PreparedStatement对象来执行CRUD练习。
1.PreparedStatement版本的CRUD练习
前面一篇我们例子就是查询练习,所以,下面写插入,更新,删除三个Junit测试用例。
package com.anthony.login;
import java.sql.Connection;
import java.sql.PreparedStatement;
import org.junit.Test;
import com.anthony.utils.DBUtils;
public class PreparedStatementCRUD {
@Test
public void testInsert() {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DBUtils.getConnection();
stmt = conn.prepareStatement("INSERT INTO student VALUES(?,?,?,?,?)");
stmt.setString(1, "192107");
stmt.setString(2, "ZS");
stmt.setString(3, "male");
stmt.setString(4, "19");
stmt.setString(5, "abc");
int i = stmt.executeUpdate();
if( i > 0) {
System.out.println("Success");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtils.close(conn, stmt, null);
}
}
@Test
public void testUpdate() {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DBUtils.getConnection();
stmt = conn.prepareStatement("UPDATE student SET Name=? WHERE ID=?");
stmt.setString(1, "Lisi");
stmt.setString(2, "192107");
int i = stmt.executeUpdate();
if( i > 0) {
System.out.println("Success");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtils.close(conn, stmt, null);
}
}
@Test
public void testDelete() {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DBUtils.getConnection();
stmt = conn.prepareStatement("DELETE FROM student WHERE Name=? AND ID=?");
stmt.setString(1, "Lisi");
stmt.setString(2, "192107");
int i = stmt.executeUpdate();
if( i > 0) {
System.out.println("Success");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtils.close(conn, stmt, null);
}
}
}
2.JDBC总结
1)什么是JDBC
Java语言操作数据库的一种规范。
2)JDBC中四个核心对象
DriverManager类 | 用来加载注册驱动 |
Connection接口 | 获取连接数据库的连接对象 |
Statement/PreparedStatement接口 | 执行SQL语句功能,第二个用来防止SQL注入,性能更高 |
ResultSet接口 | 存储操作SQL语句的结果集,用于后续数据操作 |
3) 注册驱动,记得我们使用反射的方式,Class.forName("com.mysql.jdbc.Driver")
4) 提取数据库连接信息到properties配置文件。
5)sql注入和PreparedStatement解决该问题