1.原生态JDBC编程详解与问题总结
2016-05-08 23:42
411 查看
1.首先导入jar包
第一个为mysql驱动包
第二个为oracle驱动包
2.以下步骤见代码
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; /** * jdbc编程 * @author asdc * */ public class TestJDBC { public static void main(String[] args) { //使用数据库连接 Connection connection = null; //使用预编译statement,使用预编译statement提升数据库性能 PreparedStatement preparedStatement = null; //结果集 ResultSet resultSet = null; try { //1.加载数据库驱动包 Class.forName("com.mysql.jdbc.Driver"); //2.通过驱动管理获取数据库连接 connection = DriverManager.getConnection(""); //3.定义sql语句 String sql = "select * from Users where id = ?"; //4.获取预处理statement,设置参数 preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, "1111"); //5.向数据库发出sql执行查询,查出结果集 resultSet = preparedStatement.executeQuery(); //6.遍历查询结果集 while(resultSet.next()){ System.out.println(resultSet.getString("id")+","+resultSet.getString("userName")); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{//释放资源 从下向上释放 if(resultSet != null){ try { resultSet.close(); } catch (Exception e2) { // TODO: handle exception } } if(preparedStatement != null){ try { preparedStatement.close(); } catch (Exception e2) { // TODO: handle exception } } if(connection != null){ try { connection.close(); } catch (Exception e2) { // TODO: handle exception } } } } }
3.问题总结
①.数据库连接用的时候创建开启,不用的时候关闭,频繁操作数据库。影响数据库性能解决方案:使用数据库连接池
②使用sql查询时使用的硬编码到java代码中,如果需要修改sql语句需要重新编译java代码,不利于系统维护
解决方案:将sql语句配置到xml中,即使sql发生变化也不需要重新编译java代码
③向preparedStatement中设置参数,对占位符位置设置参数时,硬编码到java代码中,不利于系统维护
解决方案:配置到xml中,即使sql发生变化也不需要重新编译java代码
④从结果集中查询时存在硬编码如:resultSet.getString(“id”)
解决方案:查询完成直接映射成对象
相关文章推荐
- jdbc中的Statement和PreparedStatement接口对象
- MySQL中的integer 数据类型
- MySQL存储过程
- 基于 Red Hat 的发行版 Oracle Linux 正式发布Oracle Linux 7.1
- mysql中int、bigint、smallint 和 tinyint的区别与长度
- mysql load data 导出、导入 csv
- source命令执行SQL脚本文件
- MySQL创建用户及权限控制
- MySQL管理数据表
- linux下mysql添加用户
- mysql procedure
- mysql触发器
- Oracle Containers for J2EE远程安全漏洞(CVE-2014-0413)
- Oracle 10g R2不能使用EM的问题
- MySQL 备份和恢复策略
- 表空间操作
- PreparedStatement中in子句的处理
- mac下安装mysql(转载)