JDBC原生态开发的过程:
public static void main(String[] args) {
//数据库连接对象
Connection con = null;
//预编译的Statement,通过Statement操作数据库,使用预编译的Statement提高数据库性能
PreparedStatement ps= null;
//结果集
ResultSet rs = null;
try {
//加载数据库驱动
Class.forName(“com.mysql.jdbc.Driver”);
//通过驱动管理类获取数据库链接
con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/mybatis”,”root”, “root”);
//定义sql语句 ?表示占位符
String sql = “select * from user where username=?”;
//获取预处理statement
ps = con.prepareStatement(sql);
//设置参数,第一个参数为sql语句中参数的序号(从1开始) 第二个参数为设置的参数值
ps .setString(1,”王五”);
//向数据库发出sql执行查询,查询出结果集
rs = ps.executeQuery();
//遍历查询结果集
while(rs.next()) {
System.out.println(rs.getString(“id”)+”::”+rs.getString(“username”));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
//释放资源
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
问题总结:
1.数据库连接使用时连接,不使用时释放:对数据库频繁的开启和关闭,造成数据库资源浪费;
解决:使用数据库连接池管理数据库连接。
2.将sql语句硬编码到Java代码中,若sql需要修改,则需要重新编写sql语句,不利于系统维护;
解决:将sql语句配置在xml配置文件中,即使sql变化,也不需要对Java代码重新编译。
3.向preparedStatement中设置参数,对占位符位置和设置参数,硬编码在Java代码中,不利于系统维护;
解决:将sql语句及占位符及参数全部配置在xml配置文件中。
4.从resultSet中遍历结果集数据时,存在硬编码,将获取表中的字段进行硬编码,不利于系统维护;
解决:将查询的结果集,自动映射成Java对象。