JDBC

一、什么是JDBC

1、JDBC概念

  • JDBC:Java DataBase Connecivity java,数据库连接或java语言操作数据库

2、JDBC本质

  • 其实是官方(sun公司)定义的一套操作所有关系型数据库的规则,即接口。各大数据库厂商去实现这套接口,提供数据库jar包。我们可以使用这套接口编程,真正执行的代码是驱动jar包中的实现类。
    String url=“jdbc:mysql://localhost:3306/class?serverTimezone=UTC”;
    jdbc:mysql://IP地址(域名):端口号/表名?serverTimezone=UTC

二、管理事务

假如银行转账系统 从张三的账户转1000元到小罗的账户 这个操作需要分两步
1.张三账户减少1000元
2.小罗账户增加1000元 假如于到断电等等,而刚好张三减了1000,而此时小罗却不增加,可以想象银行这下有事做了。

所以使用事务操作数据来搞定

1、 setAutoCommit(Boolean autoCommit);设置是否自动提交事务;

执行sql之前开启

2 、commit();提交事务

当所有sql执行完之提交事务

3、 rollback();回滚事务

在catch中回滚事务

public void execUpdate(String sql) {
       ResultSet rs=0;
       String name="xcz";      
       Connect con=JDBCUtil.getconnection();
       //开启事务
        con.setAutoCommit(false);
        try {      
              String sql="select* from stu where name=’ “+name+” ’ ";        
              Statement statem=con.createStatement();
              rs=statm.executeQuery(sql);
               //提交事务
              con.commit();
              while(rs.next()){
                  String id=rs.getString("id");
                  System.out.println(id);
              }
        } catch (SQLException e) {
              if(con!=null){
                try {
                //回滚事务
                   con.rollback();
               }catch (SQLException e1) {
                   e1.printStackTrace();
               }finally{
                 JDBCUtil.close();
               }
           }
        }
    }
  • java使用事务非常简单,首先调用conn.setAutoCommit(boolean b)方法,传入一个false,这样将不会自动提交,而需要使用conn.commit()方法,手动提交事务,当然只有在确认两个步骤都没有出错的情况下,才能提交,这样才能保证整个操作的完整性,一旦出错,使用conn.rollback()方法,回滚事务,这样的话,整个事务都将不被提交。那么如何判断有没有出错呢,非常简单,执行数据库操作的方法,都会抛出java.sql.SQLException,所以需要使用try……catch语句块捕获异常,在catch块中,使用conn.rollback()回滚事务即可在数据库调用的javabean中conn.setAutoCommit()的功能是每执行一条SQL语句,就作为一次事务提交。但一般在项目中很有可能需要执行多条SQL语句作为一个事务。若有一个执行不成功,就会rollback();

  • 一般来讲,大家对数据库中的表单,主要是增、删、改、查 这四个操作,如果你的程序当中,遇到一次业务逻辑需要两次或两次以上的对相同数据表的增删改操作,那么,为了数据的一致性,(或者具体说,在你的一次业务逻辑的处理过程中,其他(线程或程序或业务处理)的对相同数据的相同两次查询所得结果相同。)我们会利用数据库的事务操作,将一次业务逻辑所包含的所有操作封装在一个事务里,一次将多个操作进行提交。
    而conn的setAutoCommit方法,是指,在事务当中,是否执行一条语句就自动提交一次。想在一个事务里进行多个操作。就必然将setAutoCommit的参数设置成false,在多个操作的最后调用conn.commit()方法,进行手动提交

  • 参数:true和false
    假设如下:
    1 、数据库一个表格有50条记录
    2、 你设置参数为false
    则在你执行整个查询SQL期间,一直是没有事务的,那么如果你的查询用到了一些函数,这些函数包含了多个查询语句,那么有可能会出现不一致的情况。
    也就是说,函数、存储过程等,他们都将运行在非事务的环境下。
    而你设置为true,则没有任何问题了,读一致性将保证不会出现问题。

三、JDBCUtil类(JDBC工具类)

1、没有配置文件

package Login;
import java.sql.*;     //导入java.sql包
public class JDBCUtil {//创建Login类,保证文件名与类名相同
   private static final String driver = "com.mysql.jdbc.Driver";
   private static final String url = "jdbc:mysql://cdb-4zq7z550.bj.tencentcdb.com:10078/JDBC";
  //连接本地数据库
  // final String  url="jdbc:mysql://localhost:3306/class?serverTimezone=UTC";
  // (无敌连接代码)final String  url="jdbc:mysql://localhost:3306/class?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";

   private static final String user = "xcz";
   private static final String password = "19980625xcz";
   public static Connection con = null;
   static PreparedStatement preparedStatement = null;
   static ResultSet resultSet= null;
   public static Connection getConnection() {  //建立返回值为Connection的方法
       try {        //加载数据库驱动类
           Class.forName(driver);
           System.out.println("数据库驱动加载成功");
       } catch (ClassNotFoundException e) {
           e.printStackTrace();
       }
       try {
           //连接腾讯云MySQL
           con = DriverManager.getConnection(url, user, password);//通过访问数据库的URL获取数据库连接对象
           System.out.println("数据库连接成功");
       } catch (SQLException e) {
           e.printStackTrace();
       }
       return con;//按方法要求返回一个Connection对象
   }
   public static void close(Connection connection, Statement statement,ResultSet resultSet) {
       if(resultSet != null) {
           try {
               resultSet.close();
               System.out.println("resultSet.close()");
               } catch (SQLException e) {
               e.printStackTrace();
           }
       }
       if(statement != null) {
           try {
               statement.close();
               System.out.println("statement.close()");
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }
       if(connection != null) {
           try {
               connection.close();
               System.out.println("connection.close()");
           } catch (SQLException e) {
               e.printStackTrace();
           }
       }
   }

//    public static void main(String[] args) {
//        getConnection();
//    }
}

2、使用配置文件

在这里插入图片描述
jdbc.properties文件

url=jdbc:mysql://localhost:3306/library?serverTimezone=UTC
user=root
password=123456
driver=com.mysql.cj.jdbc.Driver
package cn.my.util;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
public class JDBCUtil {
    private static String url;
    private static String user;
    private static String password;
    private static Connection con;
    private static String driver;
    /**
     * 静态代码块,自动执行,只执行一次
     */
    static {
        //创建Properties类的对象
        Properties properties=new Properties();
        //类加载器
        ClassLoader classLoader=JDBCUtil.class.getClassLoader();
        //获得src目录下的jdbc.properties文件目录,返回是URL类型
        URL resource=classLoader.getResource("jdbc.properties");
        //得到文件路径,String类型
        String path=resource.getPath();
        System.out.println(path);
        try {
            //加载文件
            properties.load(new FileReader(path));
            //文件获取相应的值
            url=properties.getProperty("url");
            user=properties.getProperty("user");
            password=properties.getProperty("password");
            driver=properties.getProperty("driver");
            Class.forName(driver);
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public  static Connection getConnect(){
        try {
            con=DriverManager.getConnection(url,user,password);
            System.out.println("数据库连接成功");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return con;
    }
    public static void close(Statement st, ResultSet re, Connection con){
        if(st!=null){
            try {
                st.close();
                System.out.println("Statement关闭");
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        else if(re!=null){
            try {
                re.close();
                System.out.println("ResultSet关闭");
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        else if(con!=null){
            try {
                con.close();
                System.out.println("Connection关闭");
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
//    public static void main(String[] args) {
//        getConnect();
//    }

}

四、调用JDBC工具类

package numble;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Random;
public class Test {
    public static void main(String[] args) throws SQLException {
        Connection con;
        PreparedStatement preparedStatement;
        con = JDBCUtil.getConnection();//此处调用JDBC工具类
        int count=0;
        for (int i = 1; i <= 1000; i++) {
            preparedStatement = con.prepareStatement("insert into aaa(a,b) values(?,?)");
            Random random = new Random();
            int x = random.nextInt(500)+1000;
            preparedStatement.setInt(1, i);
            preparedStatement.setInt(2, x);
            preparedStatement.executeUpdate();
            count++;
        }
        con.close();
        System.out.println(count+"条数据被插入");
    }
}

五、Statement 和PreparedStatement

1、Statement

public void execUpdate(String sql) {
    ResultSet rs;
    String name="xcz";      
    Connect con=JDBCUtil.getconnection();
     try {
           /*String sql="select* from stu where name=?";
           PreparedStatement pstmt=con.prepareStatement(sql);
           pstmt.setString(1,name);
           rs=pstmt.executeQuery();*/      
           String sql="select* from stu where name=’ “+name+” ’ ";        
           Statement statem=con.createStatement();
           rs=statm.executeQuery(sql);
           while(rs.next()){
               String id=rs.getString("id");
               System.out.println(id);
           }
     } catch (SQLException e) {
         e.printStackTrace();
     }
 }

2、PreparedStatement

public void execUpdate(String sql) {
       private PreparedStatem pstmt;
       int rtn=0;
       String name="xcz";    
       ResultSet set;   
       Connect con=JDBCUtil.getconnection();
        try {
              String sql="select* from stu where name=?";
              pstmt=con.prepareStatement(sql);
              pstmt.setString(1,name);
              set=pstmt.executeQuery();
              int row=0; 
              while(set.next()){
               Sustem.out.println(set.getString(1));
               //获取行数
               row++;
              }           
            } catch (SQLException e) {
                       e.printStackTrace();
                  }
      }

3、参数传递

  • Statement 的变量传递为:’ “+变量+” ’
  • String sql="select* from stu where name=’ “+name+” ’ ";
  • PreparedStatement的变量传递为:?
  • String sql=“insert into numble(id,numble) values(?,?)”;
  • String sql=“select* from stu where name=?”;
    注意:

Statement statem=con.createStatement();
set=state.executeQuery(sql);

PreparedStatement pstmt=con.prepareStatement(sql);
set=pstmt.executeQuery();

六、数据库连接池

1、概念

其实就是一个容器(集合),存放数据库连接的。
当系统初始化完成后,容器被创建,容器会申请一些连接对象。当用户来访问数据库时,从容器中获取连接对象,用户访问完之后,会将连接对象还给容器。

2、好处

  • 节约资源
  • 用户访问高效果

3、实现

  • 标准接口:DataSource javax.spl包下的
  • 方法:
    1、获取连接: getConnection();、
    2、归还连接:如果连接对象Connection是从连接池获取的,那么Connection.close()方法,则不会关闭连接,而是归还连接。
  • 一般我们不去实现它,由数据库厂商来实现
    (1)c3p0 数据库连接技术
    (2)Druid 数据库连接技术,阿里巴巴提供(高效)

(1)c3p0

步骤

①导入jar包(3个)c3p0-0.9.5.2.jar,mchange- commons-java-0.2.12.jar ,mysql-connector-java-8.0.20.jar(不要忘记加mysql驱动) 导入jar包详见
②定义配议文件:
名称: c3p0.properties或者c3p0-config.xml
路径:直接将文件放在src目录下即可。
③创建核心对象数据库连接池对象ComboPooledDatasource
④获取连接: getconrectfon

  • c3p0-config.xml文件代码

<c3p0-config>
    <!--使用默认的配置读取数据库连接池对象 -->
    <default-config>
        <!--  连接参数 -->
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/library?serverTimezone=Asia/Shanghai</property>
        <property name="user">root</property>
        <property name="password">123456</property>
        <!-- 连接池参数 -->
        <!--初始化申请的连接数量-->
        <property name="initialPoolSize">5</property>
        <!--最大的连接数量-->
        <property name="maxPoolSize">10</property>
        <!--超时时间-->
        <property name="checkoutTimeout">3000</property>
    </default-config>

        <named-config name="otherc3p0">
            <!--  连接参数 -->
            <property name="driverClass">com.mysql.jdbc.Driver</property>
            <property name="jdbcUrl">jdbc:mysql://localhost:3306/hs_test?serverTimezone=Asia/Shanghai</property>
            <property name="user">root</property>
            <property name="password">root</property>
            <!-- 连接池参数 -->
            <property name="initialPoolSize">5</property>
            <property name="maxPoolSize">8</property>
            <property name="checkoutTimeout">1000</property>
        </named-config>
</c3p0-config>

DataSource ds = new  ComboPooledDataSource(" mySource ");
//参数对应使用哪个config,如果不写,表示使用默认的config,
即default-config里的配置,否则使用参数指定的named-config里的配置。
  • c3p0.properties(名字不是固定)

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/website?useUnicode=true&characterEncoding=utf8&useSSL=false
username=root
password=123456

# 初始化连接数量
initialSize=5
# 最大连接数
maxActive=10
# 最大等待时间
maxWait=3000

c3p0测试代码

package cn.sun.test;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class C3P0Test {
    public static void main(String[] args) throws SQLException {
    /*
       使用c3p0-config.xml文件中<named-config name="otherc3p0">设置的配置
       DataSource dataSource=new ComboPooledDataSource("otherc3p0");
    */
    //使用<default-config>默认配置
        DataSource dataSource=new ComboPooledDataSource();
        Connection connection=dataSource.getConnection();
        System.out.println(connection);
        PreparedStatement preparedStatement;
        ResultSet resultSet;
        preparedStatement=connection.prepareStatement("select * from books_table");
        resultSet=preparedStatement.executeQuery();
        while(resultSet.next()) {
            System.out.println(resultSet.getInt(1));
        }
        //归还连接
        connection.close();
    }
}

(2)Druid

步骤

1、导入jar包 druid-1.0.9.jar,mysql-connector-java-8.0.20.jar
2、定义配置文件:是properties形式的
可以叫任意名称,可以放在任意目录下
3、加载配置文件,Properties

 Properties pro = new Properties();
 InputStream is=DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties");
 pro.load(is);

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

DataSource ds = DruidDataSourceFactory.createDataSource(pro);

5、获取连接:getConnection

Connection conn = ds.getConnection();

druid.properties

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/library?serverTimezone=UTC
username= root
password= root
#初始化连接数量
initialSize=5
#最大连接数
maxActive=10
#最大等待时间
maxWait=3000

Druid JDBCUtil工具类

 * 代码:
        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();
            }
            /**
             * 释放资源
             */
            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();
                    }
                }*/
               close(null,stmt,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();
                    }
                }
            }
            /**
             * 获取连接池方法
             */
            public static DataSource getDataSource(){
                return  ds;
            }
        }

(3)Spring JDBC

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

步骤

1、导入jar包

2、创建JdbcTemplate对象。依赖于数据源DataSource

JdbcTemplate template = new JdbcTemplate(ds);

3、调用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:查询结果,将结果封装为对象,一般用于聚合函数的查询
* 需求:
            1. 修改1号数据的 salary 为 10000
            2. 添加一条记录
            3. 删除刚才添加的记录
            4. 查询id为1的记录,将其封装为Map集合
            5. 查询所有记录,将其封装为List
            6. 查询所有记录,将其封装为Emp对象的List集合
            7. 查询总记录数
        * 代码:
            import cn.itcast.domain.Emp;
            import cn.itcast.utils.JDBCUtils;
            import org.junit.Test;
            import org.springframework.jdbc.core.BeanPropertyRowMapper;
            import org.springframework.jdbc.core.JdbcTemplate;
            import org.springframework.jdbc.core.RowMapper;
            import java.sql.Date;
            import java.sql.ResultSet;
            import java.sql.SQLException;
            import java.util.List;
            import java.util.Map;
            public class JdbcTemplateDemo2 {
                //Junit单元测试,可以让方法独立执行//1. 获取JDBCTemplate对象
                private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
                /**
                 * 1. 修改1号数据的 salary 为 10000
                 */
                @Test
                public void test1(){
                    //2. 定义sql
                    String sql = "update emp set salary = 10000 where id = 1001";
                    //3. 执行sql
                    int count = template.update(sql);
                    System.out.println(count);
                }
                /**
                 * 2. 添加一条记录
                 */
                @Test
                public void test2(){
                    String sql = "insert into emp(id,ename,dept_id) values(?,?,?)";
                    int count = template.update(sql, 1015, "郭靖", 10);
                    System.out.println(count);
                }
                /**
                 * 3.删除刚才添加的记录
                 */
                @Test
                public void test3(){
                    String sql = "delete from emp where id = ?";
                    int count = template.update(sql, 1015);
                    System.out.println(count);
                }
                /**
                 * 4.查询id为1001的记录,将其封装为Map集合
                 * 注意:这个方法查询的结果集长度只能是1
                 */
                @Test
                public void test4(){
                    String sql = "select * from emp where id = ? or id = ?";
                    Map<String, Object> map = template.queryForMap(sql, 1001,1002);
                    System.out.println(map);
                    //{id=1001, ename=孙悟空, job_id=4, mgr=1004, joindate=2000-12-17, salary=10000.00, bonus=null, dept_id=20}
                }
                /**
                 * 5. 查询所有记录,将其封装为List
                 */
                @Test
                public void test5(){
                    String sql = "select * from emp";
                    List<Map<String, Object>> list = template.queryForList(sql);
                    for (Map<String, Object> stringObjectMap : list) {
                        System.out.println(stringObjectMap);
                    }
                }
                /**
                 * 6. 查询所有记录,将其封装为Emp对象的List集合
                 */
                @Test
                public void test6(){
                    String sql = "select * from emp";
                    List<Emp> list = template.query(sql, new RowMapper<Emp>() {
                        @Override
                        public Emp mapRow(ResultSet rs, int i) throws SQLException {
                            Emp emp = new Emp();
                            int id = rs.getInt("id");
                            String ename = rs.getString("ename");
                            int job_id = rs.getInt("job_id");
                            int mgr = rs.getInt("mgr");
                            Date joindate = rs.getDate("joindate");
                            double salary = rs.getDouble("salary");
                            double bonus = rs.getDouble("bonus");
                            int dept_id = rs.getInt("dept_id");
                            emp.setId(id);
                            emp.setEname(ename);
                            emp.setJob_id(job_id);
                            emp.setMgr(mgr);
                            emp.setJoindate(joindate);
                            emp.setSalary(salary);
                            emp.setBonus(bonus);
                            emp.setDept_id(dept_id);
                            return emp;
                        }
                    });
                    for (Emp emp : list) {
                        System.out.println(emp);
                    }
                }
                /**
                 * 6. 查询所有记录,将其封装为Emp对象的List集合
                 */
                @Test
                public void test6_2(){
                    String sql = "select * from emp";
                    List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
                    for (Emp emp : list) {
                        System.out.println(emp);
                    }
                }
                /**
                 * 7. 查询总记录数
                 */
                @Test
                public void test7(){
                    String sql = "select count(id) from emp";
                    Long total = template.queryForObject(sql, Long.class);
                    System.out.println(total);
                }
            }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值