数据库(下)
JDBC工具类封装
按照之前的步骤的话,我们可以发现有好多的步骤都是重复操作的,我们没有必要重复的书写,为了省事,我们可以把这些重复使用的部分给封装起来。
可以封装的步骤:
1. 数据库连接对象java.sql.Connection获取过程
2. 关闭资源
public class JdbcUtil{
private static String url = null;
private static String user = null;
private static String password = null;
//利用static修饰的静态代码块完成文件字段自动读取和驱动
static{
try {
Properties properties = new Properties();
properties.load(new FileInputStream("./src/db.properties"));
String driverClass = properties.getProperty("driverClass");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
//驱动加载
Class.forName(driverClass);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
//数据库连接对象
public static Connection getConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
//处理数据库操作对应的资源问题
public static void close(Connection connection) {
close(connection, null, null);
}
public static void close(Connection connection, Statement statement) {
close(connection, statement, null);
}
//close方法
public static void close(Connection connection, Statement statement, ResultSet resultSet){
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
我们db.properties文件在src目录下,内容
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/lalala?useSSL=true
user=root
password=123456
SQL语句注入问题
之前我们查询的时候使用的是Statement查询,但是有一个潜在的问题:比如我们要查询一个数据,这个数据需要根据它的用户名和对应的密码才能正确查到 select * form table where username= ‘xxx’ and password = ‘123456’;正常来说是这样的,但是我们可以通过一些处理可以将password处理掉:
select * from table where username = ‘xxx’ and password= ‘aaaaaa’ or 1=1 --’
我们输入(aaaaaa’ or 1=1 – )在sql语句的末尾加上了1=1,这个恒为真,所以哪怕输入错误的信息,只要有这个1=1,我们还是可以查到全部数据
为了解决这样的问题我们可以使用PreparedStatement
PreparedStatement
插入操作(以插入操作为例,删除和修改步骤是一样的,只是sql语句有所不同)
//获取连接对象
Connection connection = JdbcUtil.getConnection();
//sql语句,?占位符,可以通过后面重新赋值
String sql = "insert into user(id, userName, password) VALUE (?,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//赋值
User user = new User(10, "小明", "123456");
preparedStatement.setObject(1, user.getId());
preparedStatement.setObject(2, user.getUserName());
preparedStatement.setObject(3, user.getPassword());
// 使用PreparedStatement执行SQL语句
int affectedRows = preparedStatement.executeUpdate();
最后的时候别忘记关闭资源 JdbcUtil.close(connection, preparedStatement)