Java jdbc使用 浅析JDBC如何使用

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java jdbc使用 浅析JDBC如何使用

陈全蛋   2021-03-16 我要评论
想了解浅析JDBC怎样使用的相关内容吗,陈全蛋在本文为您仔细讲解Java jdbc使用的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java,jdbc,Java,jdbc使用,下面大家一起来学习吧。

1.使用步骤:

  1. 导包
  2. 加载驱动类class.forName(....)
  3. DriverManager获取sql对象
  4. 写sql语句
  5. Statement与prepareStatement不一样的执行sql语句,前者是直接sql对象 . 执行语句,而后者是预处理,即在创建sql对象时,就用sql语句,最后在用对象执行操作。

2.JDBCUtils工具类:

就是把使用步骤的共性,提出来,放在一个类中,这样以后就能直接调用创建sql对象的方法就行了。

值得一提的是,如果我们使用配置文件,扩展性更好,在使用其他数据库时,我们只需要更改配置文件properties。获取配置文件可以使用properties对象。获取jar包的绝对路径可以使用classLoader类加载器。这样我们就不用自己添加路径了。

public class JDBCUtils {
 private static String url;
 private static String user;
 private static String password;
 private static String driver;
 /**
  * 文件的读取,只需要读取一次即可拿到这些值。使用静态代码块
  */
 static{
  //读取资源文件,获取值。
 
  try {
  //1. 创建Properties集合类。
  Properties pro = new Properties();
 
  //获取src路径下的文件的方式--->ClassLoader 类加载器
  ClassLoader classLoader = JDBCUtils.class.getClassLoader();
  URL res = classLoader.getResource("jdbc.properties");
  String path = res.getPath();
  
  //2. 加载文件
  pro.load(new FileReader(path));
 
  //3. 获取数据,赋值
  url = pro.getProperty("url");
  user = pro.getProperty("user");
  password = pro.getProperty("password");
  driver = pro.getProperty("driver");
  //4. 注册驱动
  Class.forName(driver);
  } catch (IOException e) {
  e.printStackTrace();
  } catch (ClassNotFoundException e) {
  e.printStackTrace();
  }
 }
 
 
 /**
  * 获取连接
  * @return 连接对象
  */
 public static Connection getConnection() throws SQLException {
 
  return DriverManager.getConnection(url, user, password);
 }
 
 /**
  * 释放资源
  * @param stmt
  * @param conn
  */
 public static void close(Statement stmt,Connection conn){
  if( stmt != null){
  try {
   stmt.close();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  }
 
  if( conn != null){
  try {
   conn.close();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  }
 }
 
 
 /**
  * 释放资源
  * @param stmt
  * @param conn
  */
 public static void close(ResultSet rs,Statement stmt, Connection conn){
  if( rs != null){
  try {
   rs.close();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  }
 
  if( stmt != null){
  try {
   stmt.close();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  }
 
  if( conn != null){
  try {
   conn.close();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  }
 }
 
 }

3.DBC控制事务

在执行sql语句时,如果程序执行过程中,发生了异常。比如有两个sql语句,一个是转账操作,一个人存转的这笔钱,如果第一个操作结束后发生了异常。那么这笔钱就会不翼而飞,所以为了避免这样的情况,可以使用事务。

具体操作

  1. 开启事务:setAutoCommit( boolean autoCommit ) :调用该方法设置参数为false,即开启事务。
  2. 提交事务:commit( )当所有sql都执行完提交事务。
  3. 回滚事务:rollback( ) 在catch中回滚事务。
public static void main(String[] args) {
 PreparedStatement pstmt1 = null;
 PreparedStatement pstmt2 = null;
 Connection con = null;


 try {
 con = JDBCUtils.getConnection();
 //开启事务
 con.setAutoCommit(false);
 //2.1 张三 - 500
 String sql1 = "update account set balance = balance - ? where id = ?";
 //2.2 李四 + 500
 String sql2 = "update account set balance = balance + ? where id = ?";


 pstmt1 = con.prepareStatement(sql1);
 pstmt2 = con.prepareStatement(sql2);


 //4. 设置参数,sql语句里的问号
 pstmt1.setDouble(1,500);//填第一个数据
 pstmt1.setInt(2,1);//填第二个数据


 pstmt2.setDouble(1,500);
 pstmt2.setInt(2,2);
 //5.执行sql
 pstmt1.executeUpdate();
 // 手动制造异常
 int i = 3/0;


 pstmt2.executeUpdate();
 //提交事务
 con.commit();
 } catch (SQLException e) {
 e.printStackTrace();
 } catch (Exception e){
 try {
  con.rollback();
 } catch (SQLException ex) {
  ex.printStackTrace();
 }
 } finally{
 JDBCUtils.close(con,pstmt1);
 JDBCUtils.close(con,pstmt2);
 }
}

4.JDBC连接池

连接池,就是先创建好一些连接对象,要用的的时候,直接使用,提高了效率,用完之后,归还给连接池,以便其他的使用。

c3p0连接池:

1.步骤:

导入jar包 (两个) c3p0-0.9.5.2.jar mchange-commons-java-0.2.12.jar ,还需要导入数据库驱动jar包

2.定义配置文件:

名称: c3p0.properties 或者 c3p0-config.xml。
路径:直接将文件放在src目录下即可。

3.创建核心对象 数据库连接池对象 ComboPooledDataSource

4.获取连接: getConnection

代码:

//1.创建数据库连接池对象
 DataSource ds = new ComboPooledDataSource();
 //2. 获取连接对象
 Connection conn = ds.getConnection();

druid:

这个是阿里的,性能更好,效率更高。

1.步骤:

导入jar包 druid-1.0.9.jar

2.定义配置文件:

是properties形式的
可以叫任意名称,可以放在任意目录下

3.加载配置文件。Properties

4.获取数据库连接池对象:通过工厂类来获取 DruidDataSourceFactory

5.获取连接:getConnection

//3.加载配置文件
Properties pro = new Properties();
InputStream is = DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
//4.获取连接池对象
DataSource ds = DruidDataSourceFactory.createDataSource(pro);
//5.获取连接
Connection conn = ds.getConnection();

由于代码还是冗长,重复率高,所以可以自定义个工具类:

public class JDBCUtils {

    //1.定义成员变量 DataSource
    private static DataSource ds ;
   
    static{
     try {
      //1.加载配置文件
      Properties pro = new Properties();
      pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
      //2.获取DataSource
      ds = DruidDataSourceFactory.createDataSource(pro);
     } catch (IOException e) {
      e.printStackTrace();
     } catch (Exception e) {
      e.printStackTrace();
     }
    }
   
    /**
     * 获取连接
     */
    public static Connection getConnection() throws SQLException {
     return ds.getConnection();
    }

Spring JDBC

Spring框架对JDBC的简单封装。提供了一个JDBCTemplate对象简化JDBC的开发

1.步骤:

导入jar包
创建JdbcTemplate对象。依赖于数据源DataSource

JdbcTemplate template = new JdbcTemplate(ds);

2.调用JdbcTemplate的方法来完成CRUD的操作

update():执行DML语句。增、删、改语句
queryForMap():查询结果将结果集封装为map集合,将列名作为key,将值作为value 将这条记录封装为一个map集合

注意:这个方法查询的结果集长度只能是1
queryForList():查询结果将结果集封装为list集合

注意:将每一条记录封装为一个Map集合,再将Map集合装载到List集合中
query():查询结果,将结果封装为JavaBean对象

query的参数:RowMapper

一般我们使用BeanPropertyRowMapper实现类。可以完成数据到JavaBean的自动封装
new BeanPropertyRowMapper<类型>(类型.class)
queryForObject:查询结果,将结果封装为对象

一般用于聚合函数的查询

//2. 定义sql
 
//1. 获取JDBCTemplate对象
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
String sql = "update emp set salary = 10000 where id = 1001";
//3. 执行sql
int count = template.update(sql);
System.out.println(count);

这大大简化了我们curd的代码量。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们