- 基础知识
- 框架原理
- 入门程序
原生态JDBC问题
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/mybais?characterEncoding=utf-8","root","mysql");
String sql = "select * form user where username = ?";
preparedStatement.setString(1,"张山");
resultSet = preparedStatement.executeQuery();
while(resultSet.next()){
System.out.println(resultSet.getString("id")+
":"+ resultSet.getString("username"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException 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语句硬编码到java代码中,如果sql语句修改,需要重新编译
将sql语句写入xml配置文件中,修改配置文件,不需要对java代码重新编译
3、向preparedStatement设置参数,对占位符位置和设置参数全部都为硬编码在java代码中,不利于系统维护。
将sql语句及占位符和参数配置在xml中
4、从resultSet结果集数据中获取数据,获取表字样存在硬编码,不利于代码维护
查询对象的结果集,自动映射为java对象