JDBC

本文介绍了JDBC的基础知识,包括如何获取数据库连接,使用PreparedStatement进行CRUD操作,处理BLOB类型数据,以及事务的隔离级别。还讨论了在高并发下事务处理的问题和解决方案,并探讨了不同的数据库连接池技术,如DBCP、C3P0和Druid。最后,提到了Apache的dbutil包在简化增删改查操作中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JDBC概述

数据持久化

获取数据库连接

创建connection
方式一:Driver接口

public class ConnectionTest {
    @Test
    public  void  method() throws SQLException {
            Driver driver =new com.mysql.cj.jdbc.Driver();
            String url ="jdbc:mysql://localhost:3306/text";
            Properties info =new Properties();
            info.setProperty("user","root");
            info.setProperty("password","root123456");
        Connection conn =driver.connect(url,info);
        System.out.println(conn);
    }
}

方式二:

public ConnectionTest() throws ClassNotFoundException, IllegalAccessException, 
InstantiationException, SQLException {
        Class clazz =Class.forName("com.mysql.jdbc.Driver");
        Driver driver =(Driver)clazz.newInstance(); 
        String url ="XXX";
        String user ="root";
        String password ="abc132";
        DriverManager.registerDriver(driver);
        Connection conn=DriverManager.getConnection(url,user,password);
        System.out.println(conn);
    }

方式三:

@Test
    public void method() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/";
        String user = "root";
        String password = "magexiaojiao";
        Connection conn = DriverManager.getConnection(url, user, password);
        System.out.println(conn);
    }

方法四:

 @Test
    public void ConnectionTest() throws ClassNotFoundException, SQLException, IOException {
        InputStream is =ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties pros =new Properties();
        pros.load(is);
        String user =pros.getProperty("user");
        String password =pros.getProperty("password");
        String url =pros.getProperty("url");
        String driverClass =pros.getProperty("driverClass");
        //2.加载驱动
        Class.forName(driverClass);
        //3.获取连接
        Connection conn =DriverManager.getConnection(url,user,password);
        System.out.println(conn);
    }
user=root
password=magexiaojiao
url=jdbc:mysql://localhost:3306/
driverClass=com.mysql.cj.jdbc.Driver

使用 连接.PrepareStatement(注入sql)实现CRUD操作

package PrepareStatement;

import org.junit.Test;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * @Author kevin
 * @Description
 * PrepareStatement增删改
 * @Create 2021-04-04-16:18
 * @Modify
 */
public class PrepareStatementupdate {


    @Test
    public void testInsert() throws IOException, SQLException, ClassNotFoundException {
        Properties properties =new Properties();
        Class aClass = Class.forName("com.mysql.cj.jdbc.Driver");
        properties.load(new FileReader("src\\PrepareStatement\\JDBCPRO"));
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        Connection connection = DriverManager.getConnection(url,user,password);
        //预编译sql语句   获取实例
        String sql  ="insert into texttable(ID,Name,city,unkon ,telephone)value (?,?,?,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //填充占位符
        preparedStatement.setInt(1,4081);
        preparedStatement.setString(2,"shunchang");
        preparedStatement.setString(3,"ch");
        preparedStatement.setString(4,"cg");
        preparedStatement.setInt(5,106540);
        //执行操作
        preparedStatement.execute();

        connection.close();
        preparedStatement.close();

    }
}

 @Test
    public void Method() throws SQLException {
        Connection getconnectino = JDBCUtils.Getconnectino();
        String sql ="update texttable set ID=? where Name =?";
        PreparedStatement preparedStatement = getconnectino.prepareStatement(sql);
        preparedStatement.setInt(1,5000);
        preparedStatement.setString(2,"shunchang");
        preparedStatement.execute();
        JDBCUtils.Closresause(getconnectino,preparedStatement);
    }
package PrepareStatement;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @Author kevin
 * @Description
 * 操作数据库连接
 * @Create 2021-04-04-21:03
 * @Modify
 */
public class JDBCUtils {

    public static Connection Getconnectino() {
        Connection connection = null;
        try {
            Properties properties =new Properties();
            Class aClass = Class.forName("com.mysql.cj.jdbc.Driver");
            properties.load(new FileReader("src\\PrepareStatement\\JDBCPRO"));
            String user = properties.getProperty("user");
            String password = properties.getProperty("password");
            String url = properties.getProperty("url");
            connection = DriverManager.getConnection(url,user,password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
    public static void   Closresause(Connection connection, PreparedStatement preparedStatement) {
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            preparedStatement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

查询通用方法

package NormalCheckMethod;

/**
 * @autor kevin
 * @detatil
 * @create 2021-04-05-22:59
 */
public class Customer {
    public String name;
    public int age;
    public String city;

    public Customer(String name, int age, String city) {
        this.name = name;
        this.age = age;
        this.city = city;
    }

    public Customer() {
    }

    @Override
    public String toString() {
        return "Customer{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", city='" + city + '\'' +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}
package NormalCheckMethod;
import IO.FileReads;
import org.junit.Test;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.Properties;

/**
 * @autor kevin
 * @detatil
 * @create 2021-04-05-22:42
 */
public class JDBCUtils {
    public static Connection GetConnection(){
        Properties p =new Properties();
        Connection connection = null;
        try {
            p.load(new FileReader("src\\JDBC.Property"));
            String user = p.getProperty("user");
            String password = p.getProperty("password");
            String url = p.getProperty("url");
            String driverClass = p.getProperty("driverClass");
            driverClass.getClass();
            connection = DriverManager.getConnection(url,user,password);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
    public static void Closeresouse(Connection connection, ResultSet resultSet, PreparedStatement preparedStatement){
        try {
            if (connection !=null){
                connection.close();
            }
            if ((resultSet != null)) {
                resultSet.close();
            }
            if (preparedStatement !=null){
                preparedStatement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static Object Check(Connection connection,String s,Object ...args){
        ResultSet resultSet =null;
        PreparedStatement preparedStatement =null;
        try {
            preparedStatement = connection.prepareStatement(s);
            for (int i = 0; i <args.length ; i++) {
                preparedStatement.setObject(i+1,args[i]);
            }
            resultSet = preparedStatement.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            Customer customer =new Customer();
            if(resultSet.next()){
                for (int i = 0; i <columnCount ; i++) {
                    Object object = resultSet.getObject(i + 1);
                    String columnLabel = metaData.getColumnLabel(i + 1);
                    Field declaredField = customer.getClass().getDeclaredField(columnLabel);
                    declaredField.setAccessible(true);
                    declaredField.set(customer,object);
                }
                return customer;
            }
            return null;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.Closeresouse(connection,resultSet,preparedStatement);
        }
        return null;


    }
}

BLOB处理照片视频上传问题(preparedstatement.setBlob)

TinyBlob 最大255,Blob 最大65k,MediumBlob最大16M,LongBlob最大4G
使用BLOB上传照片到数据库 preparedStatement.setBlob(5,fileInputStream)

//        try {
//            preparedStatement.setInt(1,6);
//            preparedStatement.setString(2,"json");
//            preparedStatement.setString(3,"gl");
//            preparedStatement.setLong(4, 17777373L);
//            FileInputStream fileInputStream = new FileInputStream("src\\pho.jpg");
//            preparedStatement.setBlob(5,fileInputStream);			新知识
//            preparedStatement.execute();
//        } catch (SQLException e) {
//            e.printStackTrace();
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } finally {
//            if (preparedStatement != null){
//                try {
//                    preparedStatement.close();
//                } catch (SQLException e) {
//                    e.printStackTrace();
//                }
//            }if (connect != null){
//                try {
//                    connect.close();
//                } catch (SQLException e) {
//                    e.printStackTrace();
//                }
//            }
//        }

从数据库中下载Blob照片(sql语句的运行结果放到结果集,结果集.getBlob)
Blob blob = resultSet.getBlob(“Photo”);

Connection connect = JDBCUtil.getConnect();
        InputStream binaryStream = null;
        String sql = "select Photo from texttable where ID = '5'";
        PreparedStatement preparedStatement = connect.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()){
            Blob blob = resultSet.getBlob("Photo");
            binaryStream = blob.getBinaryStream();
        }
        FileOutputStream outputStream =new FileOutputStream("src\\json.jpg");
        int k =0;
        byte[] b =new byte[1024];
        if ( (k = binaryStream.read(b))   != -1)
        for (int i = 0; i <b.length ; i++) {
            outputStream.write(b,0,k);
        }

JDBC数据库事务 getconnectino.setAutoCommit(false),getconnectino.commit()
事务:一组逻辑单元从一个状态变成另一种状态。
事务处理:保证所有作为一个工作单元执行,即使出现了故障,都不能改变这样执行方式。当在一个事务中执行多个操作时,要么所有的事物都被提交,那么这些修改就永久地保存下来:要么数据库管理系统将放弃所有修改,整个事物回滚到最初状态。

package DataBaseObj;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Author kevin
 * @Description
 * @Create 2021-04-07-16:26
 * @Modify
 */
public class USER {
    public static void main(String[] args) {
        Connection getconnectino = ConnectionTest.Getconnectino();
        //取消自动提交
        try {
            getconnectino.setAutoCommit(false);
            String sql = "update student set Type =Type -1 where FlowID =?";
            ConnectionTest.testInsert(getconnectino,sql,3);
            String sql1 = "update student set Type =Type + 1 where FlowID =?";
            ConnectionTest.testInsert(getconnectino,sql1,2);
            //数据操作完成,自动提交
            getconnectino.commit();
            //关闭连接,结束线程,一个事物结束
            ConnectionTest.Closresause(getconnectino,null);
        } catch (SQLException e) {
            try {
                getconnectino.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }finally{
				try{
						conn.setAutoCommit(true);{
}catch(SQLException e){
						e.printStackTrace();
}
}
}
            e.printStackTrace();
        }
    }
}
package DataBaseObj;

import Practice.JDBC.JDBCUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.mysql.cj.jdbc.Driver;
import org.junit.Test;

import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @Author kevin
 * @Description
 * @Create 2021-04-07-16:08
 * @Modify
 */

    public class ConnectionTest {

    public static Connection Getconnectino() {
        Connection connection = null;
        try {
            Properties properties =new Properties();
            Class aClass = Class.forName("com.mysql.cj.jdbc.Driver");
            properties.load(new FileReader("src\\PrepareStatement\\JDBCPRO"));
            String user = properties.getProperty("user");
            String password = properties.getProperty("password");
            String url = properties.getProperty("url");
            connection = DriverManager.getConnection(url,user,password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static  void testInsert(Connection connection,String sql,Object ...args){
        PreparedStatement preparedStatement =null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i <args.length ; i++) {
                preparedStatement.setObject(i+1,args[i]);
            }
            preparedStatement.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //这里不能关闭线程,给下一个用
        Closresause(null,preparedStatement);
        System.out.println("操作成功");
    }
    public static void   Closresause(Connection connection, PreparedStatement preparedStatement) {
        try {
            if (connection !=null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (preparedStatement != null) {
                preparedStatement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

事务的隔离级别

getTransactionIsolation
setTransactionIsolation(Connection.XXXXX)

高并发下的事务处理问题
1.脏读:读取一个未提交的数据
2.不可重复读:一个事务修改表后,另一个事务出于内部获取不到修改信息,除非重新获取连接
3.幻读:

针对高并发下事务处理问题的解决方式
1.Transaction_Read_commited读已提交(mysql默认)推荐
2.Transaction_Read_uncommited 读未提交(mysql可设置,脏读问题,幻读问题)
3.REPEATABLE_READ 可重复读 避免脏读和不可重复度,但还有幻读问题
4.SERIALIZABLE 串行化 确保事务可以从一个表中读取相同的行,在这个事务期间,禁止其他事务对表执行操作,所有并发问题都可以避免,但性能低下。

标准的DAO

DAO的基本实现类,封装了增删改查基本方法,任何的数据表查询都是基于此方法写表的接口和接口实现类

package StandarDAO;
import PrepareStatement.JDBCUtils;
import ReviewPrepareSTATEMENT.Connect;
import org.junit.Test;

import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * @Author kevin
 * @Description
 * @Create 2021-04-08-20:03
 * @Modify
 */
//查多条
public class BaseDAO {
    public <T> List<T> CheckAll(Connection connection, Class<T>clazz, String s, Object... args) {
        ResultSet resultSet = null;
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = connection.prepareStatement(s);
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }
            resultSet = preparedStatement.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            ArrayList<T> list = new ArrayList<>();
            while (resultSet.next()) {
                T t = clazz.getConstructor().newInstance();
                for (int i = 0; i < columnCount; i++) {
                    Object object = resultSet.getObject(i + 1);
                    String columnLabel = metaData.getColumnName(i + 1);
                    Field declaredField = clazz.getDeclaredField(columnLabel);
                    declaredField.setAccessible(true);
                    declaredField.set(t, object);
                }
                list.add(t);
            }
            return  list;
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.Closeresouse(null,resultSet,preparedStatement);
        }
        return null;
    }
//查
    public Object Check(Connection connection, Object o, String s, Object ...args){
        ResultSet resultSet =null;
        PreparedStatement preparedStatement =null;
        try {
            preparedStatement = connection.prepareStatement(s);
            for (int i = 0; i <args.length ; i++) {
                preparedStatement.setObject(i+1,args[i]);
            }
            resultSet = preparedStatement.executeQuery();
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            if(resultSet.next()){
                for (int i = 0; i <columnCount ; i++) {
                    Object object = resultSet.getObject(i + 1);
                    String columnLabel = metaData.getColumnLabel(i + 1);
                    Field declaredField = o.getClass().getDeclaredField(columnLabel);
                    declaredField.setAccessible(true);
                    declaredField.set(o,object);
                }
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } finally {
            //这里不能关闭线程,给下一个用
            JDBCUtils.Closeresouse(null,resultSet,preparedStatement);
        }
        return o;
    }
    //获取链接
    public static Connection Getconnectino() {
        Connection connection = null;
        try {
            Properties properties =new Properties();
            Class aClass = Class.forName("com.mysql.cj.jdbc.Driver");
            properties.load(new FileReader("src\\JDBC.property"));
            String user = properties.getProperty("name");
            String password = properties.getProperty("password");
            String url = properties.getProperty("url");
            connection = DriverManager.getConnection(url,user,password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
    //增删改
    public static void Update(Connection connection,String sql,Object ...args) {
        PreparedStatement preparedStatement =null;
        try {
            preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i <args.length ; i++) {
                preparedStatement.setObject(i+1,args[i]);
            }
//        try{
//        String sq = "delete from texttable where ID  =10";
//        Connection getconnectino = Getconnectino();
//        PreparedStatement preparedStatement1 = getconnectino.prepareStatement(sq);
        preparedStatement.execute();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //这里不能关闭线程,给下一个用
        Closresause(null,preparedStatement);
        System.out.println("操作成功");
    }
    public static void Closresause(Connection connection, PreparedStatement preparedStatement) {
        try {
            if (connection !=null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (preparedStatement != null) {
                preparedStatement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

这里以我本地的City表为例子,创建一个接口,里面写的City表的基本操作

package StandarDAO;

import java.sql.Connection;
import java.util.List;

/**
 * @Author kevin
 * @Description
 * @Create 2021-04-08-20:10
 * @Modify
 */
public interface CityDAO {


    void add(Connection connection, City city);
    void delete(Connection connection,int ID);
    void update(Connection connection,City city,int ID);
    List<? extends City> get(Connection connection, City city);
}

接口实现类实现city的增删改查功能

package StandarDAO;

import java.sql.Connection;
import java.util.List;

/**
 * @Author kevin
 * @Description
 * @Create 2021-04-08-20:24
 * @Modify
 */
public class CityDAOIml extends BaseDAO implements CityDAO{

    @Override
    public void add(Connection connection, City city) {
        String sql ="insert into texttable(ID,nam,city,unkon,telephone)values(?,?,?,?,?)";
        BaseDAO.Update(connection,sql,city.getID(),city.getNam(),city.getCity(),city.getUnkon(),city.getTelephone());
    }

    @Override
    public void delete(Connection connection, int ID) {
        String sql ="delete from texttable where ID = ?";
        BaseDAO.Update(connection,sql,ID);
    }

    @Override
    public void update(Connection connection, City city,int ID) {
        String sql ="update texttable set nam =? where ID = ?";
        BaseDAO.Update(connection,sql,city.getNam(),ID);
    }

    @Override
    public List<? extends City> get(Connection connection, City city) {
        BaseDAO baseDAO =new BaseDAO();
        String sql ="select ID,Name,CountryCode from city";
        List<? extends City> cities = baseDAO.CheckAll(connection, city.getClass(), sql);
        return cities;
    }

}

线程池连接技术

**DBCP速度快,稳定性差。Tomcat自带,已经不用
C3P0速度慢,稳定性可以。
BoneCP是开源组织提供的数据库连接池,速度快。
Druid 阿里技术速度快 不确定是否快于BoneCP
**
C3P0

package DatabasePool;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import javax.sql.DataSource;
import java.beans.PropertyVetoException;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @Author kevin
 * @Description
 * C3P0 测试
 *
 *
 *
 *
 * @Create 2021-04-09-10:38
 * @Modify
 */
public class DatabasePool {
    //c3p0技术
    @Test
    public void c3o0Method(){
        Connection connection = null;
        try {
            ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
            comboPooledDataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
            comboPooledDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/world");
            comboPooledDataSource.setUser("root");
            comboPooledDataSource.setPassword("magexiaojiao");
            //设置初始池子连接数。
            comboPooledDataSource.setInitialPoolSize(10);
            connection = comboPooledDataSource.getConnection();
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println(connection);
    }






    //druid技术
@Test
    public void method() throws Exception {
    Properties properties = new Properties();
    properties.load(new FileReader("src\\Druid.property"));
    DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
    Connection connection =dataSource.getConnection();
    System.out.println(connection);
}
}

DBCP

package DatabasePool;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.apache.commons.dbcp2.managed.BasicManagedDataSource;
import org.junit.Test;

import javax.sql.DataSource;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @Author kevin
 * @Description
 * @Create 2021-04-09-20:05
 * @Modify
 */
public class DBCP {
    private static  BasicDataSource dataSource =null;
    static{
        try {
            Properties pro =new Properties();
            pro.load(new FileReader("src\\Druid.property"));
            //创建一个数据库连接池
            dataSource = BasicDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

@Test
    public Connection getConnection() {
    Connection connection = null;
    try {
        connection = dataSource.getConnection();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return connection;
    }
}

druid技术

public class drupre {
   static Connection connection =  null;
   static  {
       Properties properties =new Properties();
       try {
           InputStream resourceAsStream = ClassLoader.getSystemClassLoader().getResourceAsStream("Druid.property");
           properties.load(resourceAsStream);
           DataSource dataSource = new DruidDataSourceFactory().createDataSource(properties);
           connection = dataSource.getConnection();
       } catch (Exception e) {
           e.printStackTrace();
       }

   }

        public Connection getConnection() {
        return connection;
        }
    }

Apache的dbutil包封装了标准的增删改查操作(执行方法new Queryrunner)

获取线程池下的查一条记录new BeanHandler

package dbutil;

import JDBCMATTER.Customer;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import jdk.jshell.spi.SPIResolutionException;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.junit.Test;

import javax.naming.PartialResultException;
import javax.sql.DataSource;
import java.io.FileReader;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.util.Properties;

/**
 * @autor kevin
 * @detatil
 * @create 2021-04-10-9:33
 */
public class DbutilTest {
    @Test
    //测试查询
    public  void method(){
        Properties properties =new Properties();
        InputStream resourceAsStream = ClassLoader.getSystemClassLoader().getResourceAsStream("Druid.property");
        try {
            properties.load(resourceAsStream);
            QueryRunner queryRunner = new QueryRunner();
            DataSource dataSource = new DruidDataSourceFactory().createDataSource(properties);
            Connection connection = dataSource.getConnection();
            String sql ="SELECT * FROM city WHERE ID =?";
            BeanHandler<Customer> customerBeanHandler = new BeanHandler<>(Customer.class);
            Customer afg = queryRunner.query(connection, sql, customerBeanHandler, 7);
            System.out.println(afg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    connection.close();
}

获取线程池查询多条记录 new BeanListHandler

   @Test
    public void listhaldertest() throws Exception {
        Properties properties =new Properties();
        InputStream resourceAsStream = ClassLoader.getSystemClassLoader().getResourceAsStream("Druid.property");
        properties.load(resourceAsStream);
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        Connection connection = dataSource.getConnection();
        QueryRunner queryRunner =new QueryRunner();
        String sql = "select * from city where CountryCode =?";
        BeanListHandler<Customer> customerBeanListHandler = new BeanListHandler<>(Customer.class);
        List<Customer> nld = queryRunner.query(connection, sql, customerBeanListHandler, "NLD");
        for (Object o:nld
             ) {
            System.out.println(o);
        }
		connection.close();
    }
配置文件
username=root
password=magexiaojiao7826041
url=jdbc:mysql://localhost:3306/world
driverClass=com.mysql.cj.jdbc.Driver

总结:获取连接,增删改查,关闭连接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值