原生JDBC
前言:
所有的持久层框架,都是对原生的jdbc做了封装,规避或解决了可能出现的问题。
步骤:
1、加载驱动
2、获取连接
3、获得预处理对象
4、参数填充
5、执行语句
6、封装结果集
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 通过驱动管理类获取数据库链接
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8", "root", "root");
// 定义sql语句?表示占位符
String sql = "select * from user where username = ?";
// 获取预处理statement
preparedStatement = connection.prepareStatement(sql);
// 设置参数,第⼀个参数为sql语句中参数的序号(从1开始),第⼆个参数为设置的参数值
preparedStatement.setString(1, "tom");
// 向数据库发出sql执⾏查询,查询出结果集
resultSet = preparedStatement.executeQuery();
// 遍历查询结果集
while (resultSet.next()) {
int id = resultSet.getInt("id");
String username = resultSet.getString("username");
// 封装User
USer user = new User();
user.setId(id);
user.setUsername(username);
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放资源
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
问题分析:
1、数据库连接频繁创建,释放消耗系统资源
2、sql语句存在硬编码问题,不利于维护,sql变动需要修改代码
3、使⽤preparedStatement向占有位符号传参数存在硬编码,因为sql语句的where条件不⼀定,可能多也可能少,不确定,当需要加参数时,需要修改代码
4、对结果集的封装存再硬编码,都是手动set进去的
解决思路:
1、使用数据库连接池解决连接频繁创建,释放的问题
2、将sql语句提取到配置文件中
3、使用反射,内省等技术完成结果集的自动封装