JDBC操作

100 阅读3分钟

什么是jdbc-传统的 java操作关系型数据的API 导入相关数据库的驱动包后可以通过JDBC提供的接口来操作数据库 实现JDBC的六个步骤 1:注册数据库驱动 2:获取数据库连接 3:获取传输器对象 4:传输sql执行获取结果集对象 5:遍历结果集获取西信息 6:关闭资源 案例:

package cn.tedu;

import org.junit.Test;

import java.sql.*;

public class test01 {
   @Test
   public void test01() {
      Connection conn = null;
      PreparedStatement ps = null;
      ResultSet rs = null;
      try {
         //1:获取数据库驱动
         Class.forName("com.mysql.jdbc.Driver");
         //      2:获取是数据库连接
         conn = DriverManager.getConnection("jdbc:mysql:///sdb", "root", "123456");
         //2:获取传输器对象
         ps = conn.prepareStatement("select  * from user where id>?");
//      3:传输sql执行并获取结果
         ps.setInt(1, 3);
         rs = ps.executeQuery();
//      4:处理结果
         while (rs.next()) {
            String name = rs.getString("name");
            System.out.println(name);
         }
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
//         5:关闭资源
         if (rs != null) {
            try {
               rs.close();
            } catch (SQLException e) {
               e.printStackTrace();
            } finally {
               rs = null;
            }
         }
         if (ps != null) {
            try {
               ps.close();
            } catch (SQLException e) {
               e.printStackTrace();
            } finally {
               ps = null;
            }
         }
         if (conn != null) {
            try {
               conn.close();
            } catch (SQLException e) {
               e.printStackTrace();
            } finally {
               conn = null;
            }

         }

      }
   }

      }

使用C3P0连接池整合JDBC 1:创建C3P0配置文件
[

内容:

c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql:///sdb
c3p0.user=root
c3p0.password=123456

2:创建JDBCUtils类 内容:

package cn.tedu;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class JDBCUtils {
    private  JDBCUtils(){

    }
    private static DataSource dataSource = new ComboPooledDataSource();
    public static Connection getConn(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

}

3:tset类代码更改

package cn.tedu;

import org.junit.Test;

import java.sql.*;

public class test01 {
   @Test
   public void test01() {
      Connection conn = null;
      PreparedStatement ps = null;
      ResultSet rs = null;
      try {
         //1:获取数据库驱动
//         Class.forName("com.mysql.jdbc.Driver");
         //      2:获取是数据库连接
//         conn = DriverManager.getConnection("jdbc:mysql:///sdb", "root", "123456");
         //2:获取传输器对象
         conn = JDBCUtils.getConn();
         ps = conn.prepareStatement("select  * from user where id>?");
//      3:传输sql执行并获取结果
         ps.setInt(1, 3);
         rs = ps.executeQuery();
//      4:处理结果
         while (rs.next()) {
            String name = rs.getString("name");
            System.out.println(name);
         }
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
//         5:关闭资源
         if (rs != null) {
            try {
               rs.close();
            } catch (SQLException e) {
               e.printStackTrace();
            } finally {
               rs = null;
            }
         }
         if (ps != null) {
            try {
               ps.close();
            } catch (SQLException e) {
               e.printStackTrace();
            } finally {
               ps = null;
            }
         }
         if (conn != null) {
            try {
               conn.close();
            } catch (SQLException e) {
               e.printStackTrace();
            } finally {
               conn = null;
            }

         }

      }
//
   }

      }

测试结果: 在这里插入图片描述 使用写JDBCUtils工具类作用: 1:简化代码 2:全局只有一个连接池对象 Spring 整合JDBC-管理数据源 1:导包 在这里插入图片描述 2:将数据源交给spring管理 2.1创建配置文件: 在这里插入图片描述 2.2配置文件内容:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    <property name="jdbcUrl" value="jdbc:mysql:///sdb"/>
    <property name="user" value="root"/>
    <property name="password" value="123456"/>
</bean>
</beans>

2.3,test类中代码实现:

package cn.tedu.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class test01 {
   @Test
   public void test01() {
      //创建spring容器
      ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
      //获取bean对象
      DataSource dataSource = (DataSource) context.getBean("dataSource");
      Connection conn = null;
      PreparedStatement ps = null;
      ResultSet rs = null;
      try {

         //1:获取数据库驱动
//         Class.forName("com.mysql.jdbc.Driver");
         //      2:获取是数据库连接
//         conn = DriverManager.getConnection("jdbc:mysql:///sdb", "root", "123456");
         //2:获取传输器对象
//         conn = JDBCUtils.getConn();
         conn = dataSource.getConnection();
         ps = conn.prepareStatement("select  * from user where id>?");
//      3:传输sql执行并获取结果
         ps.setInt(1, 3);
         rs = ps.executeQuery();
//      4:处理结果
         while (rs.next()) {
            String name = rs.getString("name");
            System.out.println(name);
         }
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
//         5:关闭资源
         if (rs != null) {
            try {
               rs.close();
            } catch (SQLException e) {
               e.printStackTrace();
            } finally {
               rs = null;
            }
         }
         if (ps != null) {
            try {
               ps.close();
            } catch (SQLException e) {
               e.printStackTrace();
            } finally {
               ps = null;
            }
         }
         if (conn != null) {
            try {
               conn.close();
            } catch (SQLException e) {
               e.printStackTrace();
            } finally {
               conn = null;
            }

         }

      }
//
   }

      }

2.4测试结果: 在这里插入图片描述 Spring 整合JDBC-模板类 1:创建spring配置类文件applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    <property name="jdbcUrl" value="jdbc:mysql:///sdb"/>
    <property name="user" value="root"/>
    <property name="password" value="123456"/>

</bean>
    <!--配置JDBC模板类-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>

2.test类代码

package cn.tedu.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class test01 {
   @Test
   public void test01() {
   //1:获取spring容器
      ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//        2:获取bean对象
      JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
//       3:新增-一行代码搞定数据库操作
      jdbcTemplate.update("insert into user values (null,?,?)",("xiaomi"),23);
//       4:关闭容器
      ((ClassPathXmlApplicationContext)context).close();
   }
}

SpringJDBC-声明式事务管理 1:加配置,gitee地址: git@gitee.com:dandan77/spring-jdbc.git

加上一个运行时异常: 在这里插入图片描述 报错如下: 在这里插入图片描述 数据库结果-未插入数据库,数据管理生效: 在这里插入图片描述 问题:如果抛出的运行时异常,能回滚吗?如: 在这里插入图片描述 答案是,没有生效,回滚,为什么? 声明式事务默认只对运行时异常有用,对编译器异常没有, 因为设计者考虑到特殊原因,异常结构: 在这里插入图片描述 运行时异常,不需要显示处理,默认处理机制,向上抛,最后抛给jvm,而我们编译时异常时必须显示处理的。 如果想所有异常都抛出 在这里插入图片描述

spring JDBC 三个作用: 1:管理数据源 2:实现数据库的增删改查 3:实现数据库的事务管理