second--JDBC(事物||连接池)

事物:ACID

一句话总结:就是为了保证一起成功,一起失败

 

package com.gton.transaction;

import com.gton.JdbcUtils;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.LocalDate;

/**
 * @program: Jdbc-start
 * @description: 事物
 * @author: GuoTong
 * @create: 2020-09-01 08:52
 **/
public class TreansactionTest {
    //开启事物: void setAutoCommit(boolean  autoCommit)
    //提交事物  void commit()
    //回滚事物  void rollback()
    public static void main(String[] args) throws SQLException {
        //获取连接
        Connection connection = JdbcUtils.getConnection();
        String sql = "insert into student values(?,?,?,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //preparedStatement.setInt(1,1234);
        preparedStatement.setString(2, "chongqing");
        preparedStatement.setInt(1, 23);
        preparedStatement.setDouble(1, 52.0);
        preparedStatement.setDate(1, Date.valueOf(LocalDate.now()));

        try {
            //开启事物,不自动提交
            connection.setAutoCommit(false);
            int insert = preparedStatement.executeUpdate();
            if (insert >= 1)
                System.out.println("添加成功");
            else
                System.out.println("添加失败");
            //提交事物
            connection.commit();
        } catch (SQLException e) {
            //异常回滚
            connection.rollback();
            e.printStackTrace();
        }
        JdbcUtils.close(connection, preparedStatement);

    }
}

 

自定义数据库连接池

  • 代理对象

 

package com.gton.transaction;


import java.sql.*;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * @program: Jdbc-start
 * @description: 代理数据库连接对象
 * @author: GuoTong
 * @create: 2020-09-01 11:28
 **/
public class ProxyConnection implements Connection {

    private Connection connection;
    private SelfPool selfPool;//连接池对象
    public ProxyConnection(Connection connection,SelfPool selfPool) {
        this.connection = connection;
        this.selfPool=selfPool;
    }

    @Override
    public Statement createStatement() throws SQLException {
        return connection.createStatement();
    }

    @Override
    public PreparedStatement prepareStatement(String sql) throws SQLException {
        return connection.prepareStatement(sql);
    }

    @Override
    public CallableStatement prepareCall(String sql) throws SQLException {
        return null;
    }

    @Override
    public String nativeSQL(String sql) throws SQLException {
        return null;
    }

    @Override
    public void setAutoCommit(boolean autoCommit) throws SQLException {
        connection.setAutoCommit(autoCommit);
    }

    @Override
    public boolean getAutoCommit() throws SQLException {
        return false;
    }

    @Override
    public void commit() throws SQLException {
        connection.commit();
    }

    @Override
    public void rollback() throws SQLException {
        connection.rollback();
    }

    //归还连接
    @Override
    public void close() throws SQLException {
        selfPool.backConnection(connection);
    }

    @Override
    public boolean isClosed() throws SQLException {
        return false;
    }

    @Override
    public DatabaseMetaData getMetaData() throws SQLException {
        return null;
    }

    @Override
    public void setReadOnly(boolean readOnly) throws SQLException {

    }

    @Override
    public boolean isReadOnly() throws SQLException {
        return false;
    }

    @Override
    public void setCatalog(String catalog) throws SQLException {

    }

    @Override
    public String getCatalog() throws SQLException {
        return null;
    }

    @Override
    public void setTransactionIsolation(int level) throws SQLException {

    }

    @Override
    public int getTransactionIsolation() throws SQLException {
        return 0;
    }

    @Override
    public SQLWarning getWarnings() throws SQLException {
        return null;
    }

    @Override
    public void clearWarnings() throws SQLException {

    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
        return null;
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        return null;
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        return null;
    }

    @Override
    public Map<String, Class<?>> getTypeMap() throws SQLException {
        return null;
    }

    @Override
    public void setTypeMap(Map<String, Class<?>> map) throws SQLException {

    }

    @Override
    public void setHoldability(int holdability) throws SQLException {

    }

    @Override
    public int getHoldability() throws SQLException {
        return 0;
    }

    @Override
    public Savepoint setSavepoint() throws SQLException {
        return null;
    }

    @Override
    public Savepoint setSavepoint(String name) throws SQLException {
        return null;
    }

    @Override
    public void rollback(Savepoint savepoint) throws SQLException {

    }

    @Override
    public void releaseSavepoint(Savepoint savepoint) throws SQLException {

    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return null;
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return null;
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return null;
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
        return null;
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
        return null;
    }

    @Override
    public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
        return null;
    }

    @Override
    public Clob createClob() throws SQLException {
        return null;
    }

    @Override
    public Blob createBlob() throws SQLException {
        return null;
    }

    @Override
    public NClob createNClob() throws SQLException {
        return null;
    }

    @Override
    public SQLXML createSQLXML() throws SQLException {
        return null;
    }

    @Override
    public boolean isValid(int timeout) throws SQLException {
        return false;
    }

    @Override
    public void setClientInfo(String name, String value) throws SQLClientInfoException {

    }

    @Override
    public void setClientInfo(Properties properties) throws SQLClientInfoException {

    }

    @Override
    public String getClientInfo(String name) throws SQLException {
        return null;
    }

    @Override
    public Properties getClientInfo() throws SQLException {
        return null;
    }

    @Override
    public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
        return null;
    }

    @Override
    public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
        return null;
    }

    @Override
    public void setSchema(String schema) throws SQLException {

    }

    @Override
    public String getSchema() throws SQLException {
        return null;
    }

    @Override
    public void abort(Executor executor) throws SQLException {

    }

    @Override
    public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {

    }

    @Override
    public int getNetworkTimeout() throws SQLException {
        return 0;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }
}

 

  • 连接池对象

 

package com.gton.transaction;

import com.gton.JdbcUtils;

import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

/**
 * @program: Jdbc-start
 * @description: 自定义连接池
 * @author: GuoTong
 * @create: 2020-09-01 10:26
 **/
public class SelfPool implements DataSource {
    //第一步,需要实现DataSource接口
    //第二步,维护一个存放Connection对象的集合
    //第三部,对外提供获取连接,归还连接的方式。

    //连接池大小
    private int size;
    //连接池
    private List<Connection> list = new ArrayList<>();

    public SelfPool(int maxsize) {
        this.size=maxsize;
        try {
            for (int i = 0; i < size; i++) {
                list.add(JdbcUtils.getConnection());
            }
        } catch (Exception e){
            System.out.println("连接池初始化失败....");
            e.printStackTrace();
        }
    }
    //获取连接
    @Override
    public Connection getConnection() throws SQLException {
        Connection connection=null;
        synchronized (this) {
            if (list.size()<=0)
                return null;
            connection= list.remove(0);
        }
        return new ProxyConnection(connection,this);
    }
    // 归还连接
    public void backConnection(Connection connection) {
        synchronized (this) {
            list.add(connection);
        }
    }
    //最大容量
    public int getMaxSize() {
        return list.size();
    }
    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return getConnection();
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }

}

 

  • 测试

 

package com.gton.transaction;

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

/**
 * @program: Jdbc-start
 * @description: 测试自己写的连接
 * @author: GuoTong
 * @create: 2020-09-01 11:04
 **/
public class TestMyPool {
    public static void main(String[] args) {
        SelfPool selfPool = new SelfPool(4);
        System.out.println("连接池最大容量:"+selfPool.getMaxSize());
        int i=0;
        do {
            new Thread(()->{
                Connection connection=null;
                try {
                    connection =selfPool.getConnection();
                    System.out.println(Thread.currentThread().getName()+":"+connection);
                    Thread.sleep(10);
                    //selfPool.backConnection(connection);
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
            i++;
        } while (i<100);
    }
}

 

下一篇。。。。开源连接池技术。。。c3p0  。。druid。。。。。Springjdbctemplete。。。等等。

 

posted on 2020-09-01 19:47  白嫖老郭  阅读(81)  评论(0编辑  收藏  举报

导航