JDBC连接mysql

JDBC简介

JDBC(Java Data Connectivity,java数据库连接)是一种用于执行sql语句的JavaAPI,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。

数据库厂商使用驱动jar包实现JDBC接口,我们只需要导入相应的数据库驱动即可用统一接口访问数据库。

JDBC-MYSQL驱动下载

https://dev.mysql.com/downloads/connector/j/
在这里插入图片描述
上面为linux版本,下面为windows版本。

下载解压之后将里面的jar包放入idea项目文件夹,右键文件夹点击add as Library。
在这里插入图片描述

JDBC使用

  1. 注册驱动
  2. 获取连接
  3. 获取Statement
  4. 执行sql
  5. 关闭连接
  		//1.注册驱动
  		Class.forName("com.mysql.cj.jdbc.Driver"); //建议写,可以没有,会通过jar包中META-INF/services自动注册
  		//从properties文件中获取user=root ,password=123。
        Properties properties = new Properties();
        properties.load(new FileReader("src/mysql.properties"));
        String url="jdbc:mysql://127.0.0.1:3306/test";
		//2.获取连接
        Connection connection = DriverManager.getConnection(url,properties);
		//Connection connection = DriverManager.getConnection(url,user,password); 也可以这样
		//3.获取Statement
        Statement statement = connection.createStatement();
        //4.执行sql
  		String sql="delete from user where name='kd'";
        boolean n = statement.execute(sql);
		//5.关闭连接
        statement.close();
        connect.close();

通过结果集查询

在这里插入图片描述

		String sql="select * from user";
        ResultSet resultSet = statement.executeQuery(sql);
        while(resultSet.next()){
            int uid = resultSet.getInt(1);
            String name = resultSet.getString(2);
            String password = resultSet.getString(3);
            Date birth = resultSet.getDate(4);
            int sal = resultSet.getInt(5);
            System.out.println(uid+name+password+birth+sal);
        }
        resultSet.close();

PreparedStatement 预处理查询

  1. 用?代替sql中的参数
  2. 有效解决sql注入问题(Statement存在sql注入问题)
  3. 效率较高
		String sql="select * from user where uid=? and name=?";
        //通过连接获取preparedStatement对象
        PreparedStatement preparedStatement = connect.prepareStatement(sql);
        int uid=2;
        String name="xiaod";
        //向?赋值
        preparedStatement.setInt(1,uid);
        preparedStatement.setString(2,name);
        ResultSet resultSet = preparedStatement.executeQuery();
        
        while (resultSet.next())
        {
            String passwd = resultSet.getString(3);
            System.out.println(passwd);
        }
        resultSet.close();

事务

connection默认是自动提交的,如要开启事务,需要关闭connection的自动提交,并在事务的末尾执行connection.commit()。

	 	Class.forName("com.mysql.cj.jdbc.Driver");
        String url="jdbc:mysql://127.0.0.1:3306/test";
        Connection connection = null;
        PreparedStatement preparedStatement=null;
        try {
            connection = DriverManager.getConnection(url,"root","root");
            connection.setAutoCommit(false);//取消自动提交,可以理解成开启事务
            String sql="insert into admin values ('kk',5)";
            String sql2="insert into admin values ('kkk',6)";
			//执行sql1
            preparedStatement= connection.prepareStatement(sql);
            preparedStatement.execute();
            Savepoint savepoint = connection.setSavepoint();//设置保存点
            //执行sql2	
            preparedStatement=connection.prepareStatement(sql2);
            preparedStatement.execute();

            connection.commit();//提交事务
        } catch (SQLException e) {        
                connection.rollback();//出错则回滚(撤销本次事务)
                //connection.rollback(Savepoint);//回滚到上次的保存点       
            throw new RuntimeException(e);
        }finally {
        		//关闭连接
                preparedStatement.close();
                connection.close();
        }

批处理

先要在url后加入?rewriteBatchedStatements=true批处理才会生效。

			String sql="insert into admin values (?,?)";
            
            preparedStatement= connection.prepareStatement(sql);
            for (int i = 0; i < 2000; i++) {
                preparedStatement.setString(1,String.valueOf(i));
                preparedStatement.setInt(2,i);
                preparedStatement.addBatch();//将sql存储到Statement batch中
            }
            preparedStatement.executeBatch();//执行batch中的所有sql       

连接池

连接池中持有若干个Connection对象,每次需要的时候就从连接池中获取,可以减少连接的开销,减少系统资源的浪费。

1.C3P0

下载:https://sourceforge.net/projects/c3p0/
下载解压后将c3p0和mchange的jar包复制到lib目录。
在这里插入图片描述
C3P0有两种配置方式:使用setXXX配置、使用xml配置文件配置
使用setXXX配置:

  //创建数据源对象
  ComboPooledDataSource dataSource = new ComboPooledDataSource();
  //配置
  dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/test");
  dataSource.setUser("root");
  dataSource.setPassword("Njtech207209");
  dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
  //从连接池中获取连接
  Connection connection = dataSource.getConnection();
  //执行sql
  PreparedStatement preparedStatement = connection.prepareStatement("select * from user");
  ResultSet resultSet = preparedStatement.executeQuery();

使用xml配置文件配置:
在项目中src目录下创建c3p0-config.xml文件,连接池会在类目录下自动寻找c3p0-config.xml文件。
可以见到c3p0-config.xml已经配置好了连接数据库所要的信息。
c3p0-config.xml :

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
   <default-config>
      <!-- 连接数据库的4项基本参数 -->
      <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
      <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/test</property>
      <property name="user">root</property>
      <property name="password">root</property>
      <!-- 如果池中数据连接不够时一次增长多少个 -->
      <property name="acquireIncrement">5</property>
      <!-- 初始化连接数 -->
      <property name="initialPoolSize">20</property>
      <!-- 最小连接受 -->
      <property name="minPoolSize">10</property>
      <!-- 最大连接数 -->
      <property name="maxPoolSize">20</property>
      <!-- -JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量 -->
      <property name="maxStatements">0</property>
      <!-- 连接池内单个连接所拥有的最大缓存statements数 -->
      <property name="maxStatementsPerConnection">5</property>
   </default-config>
</c3p0-config>

xml配置修改后的代码:

  //创建数据源对象
  ComboPooledDataSource dataSource = new ComboPooledDataSource();
  //从连接池中获取连接
  Connection connection = dataSource.getConnection();
  //执行sql
  PreparedStatement preparedStatement = connection.prepareStatement("select * from user");
  ResultSet resultSet = preparedStatement.executeQuery();

2.德鲁伊 druid

由阿里编写的连接池实现,速率高于C3P0,推荐使用。
下载地址:https://repo1.maven.org/maven2/com/alibaba/druid/
找到最新版的druid-1.2.9.jar下载即可。
druid.properties配置文件:

url=jdbc:mysql://127.0.0.1:3306/test
username=root
password=root
driverClassName=com.mysql.cj.jdbc.Driver
# 连接池的参数

#初始化连接数
initialSize=10
#最大最大活动连接数
maxActive=20
#最大等待时间
maxWait=20000

druid采用的是创造工厂模式,用DruidDataSourceFactory.createDataSource(properties)获取数据源

 Properties properties = new Properties();
        properties.load(new FileInputStream("src/druid.properties"));
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        long begin= System.currentTimeMillis();
        //测试连接50w次的时间
        for(int i=0;i<500000;i++) {
            Connection connection = dataSource.getConnection();
            connection.close();
        }
        long end = System.currentTimeMillis();
        System.out.println(end-begin);

测试50w次连接耗时:
C3P0 : 1729,DRUID: 893

DBUtils工具

它是Apache组织提供的一个对JDBC进行简单封装的开源工具类,使用它能简化JDBC应用程序的开发,提高代码的可移植性和观赏性,同时也不会影响程序的性能。

下载链接:https://commons.apache.org/proper/commons-dbutils/download_dbutils.cgi
在这里插入图片描述
DBUtils主要实现为QueryRunner对象,主要方法:update、query、execute、batch、insert等。
其中有个重要参数:ResultSetHandler接口执行处理一个结果集对象,将数据转变并处理为任何一种形式,供其他应用使用。常用实现类如下:

BeanHandler:将结果集中的第一行数据封装到一个对应的JavaBean实例中。
BeanListHandler:将结果集中的每一行数据都封装到一个对应的JavaBean实例中,存放到List里。
MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值。
MapListHandler:将结果集中的每一行数据都封装到一个Map里,然后再存放到List
ScalarHandler:将结果集第一行的某一列放到某个对象中。(处理MySQL中的聚合函数)

具体使用:

QueryRunner queryRunner = new QueryRunner();
        //通过queryRunner将结果返回到List数组中
        String sql="select * from user";
        List<User> userList = queryRunner.query(connection,sql, new BeanListHandler<>(User.class));
        //返回单行数据
        String sql="select * from user where uid=?";
        User user = queryRunner.query(connection, sql, new BeanHandler<>(User.class),2);
        //返回单行单列对象
        String sql="select name from user where uid=1";
        Object name = queryRunner.query(connection, sql, new ScalarHandler<>());
        System.out.println(name);
        //更新
        String sql="update user set password=234 where uid=?";
        int effectRows = queryRunner.update(connection,sql,2);
        System.out.println(effectRows);
        //添加
        String sql="insert into user values(3,'kd','000','1999-03-04',2000)";
        int effectRows = queryRunner.update(connection, sql);
        System.out.println(effectRows);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值