The JDBC (b) - Use IDEA database connection, a database connection pool

1. IDEA database connection

(1) Click on the right side of IDEA interface Database
Here Insert Picture Description
(2) Click +, and then click Data Source, and finally click MySQL
Here Insert Picture Description
(3) Fill in the username and password, test the connection
Here Insert Picture Description
screen is displayed (4) successful connection
Here Insert Picture Description
(5) Select to connect database to connect jdbcstudy for example
Here Insert Picture Description
Here Insert Picture Description
after the interface (6) database jdbcstudy successful connection
Here Insert Picture Description
(7) Double-click on the table name users, open table
Here Insert Picture Description
(8) to update the modified data
Here Insert Picture Description
(9) to write SQL code
Here Insert Picture Description
(10) the connection failed, see why
Here Insert Picture Description

2. Transaction

Either all succeed or fail

  • Code implementation
    ① open transaction conn.setAutoCommit (false)
    ② a set of business is finished, commit the transaction
    defined rollback statement ③ can be displayed in a catch statement, but the default will fail rollback
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class TestTransaction2 {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;
        
        try {
            conn = JdbcUtils.getConnection();
            // 关闭数据库的自动提交,自动会开启事务
            conn.setAutoCommit(false); // 开启事务

            String sql1 = "update account set money = money-100 where name = 'A'";
            st = conn.prepareStatement(sql1);
            st.executeUpdate();

            int x = 1/0; // 报错

            String sql2 = "update account set money = money+100 where name = 'B'";
            st = conn.prepareStatement(sql2);
            st.executeUpdate();

            //业务完毕,提交事务
            conn.commit();
            System.out.println("成功!");

        } catch (SQLException e) {
            // 若果失败,则默认回滚
//            try {
//                conn.rollback();  // 如果失败则回滚事务
//            } catch (SQLException e1) {
//                e1.printStackTrace();
//            }
            e.printStackTrace();
        } finally {
            JdbcUtils.release(conn,st,rs);
        }
    }
}

3. database connection pool

Database Connectivity - finished - release
connection - release is a waste of system resources,
pooling technique: some pre-preparation resources, come on connecting pre-prepared

  • Open source data source implementation (ie brought with)
    DBCP
    C3P0
    Druid: Alibaba

After using the database connection pool, we do not need to write code to connect to the database in the development of the project!

  • To DBCP, for example
    the need to use the jar package: commons-dbcp-1.4, commons -pool-1.6

The lib directory Ass a library, written in the project file dbcpconfig.properties

  • When using connection pooling parameters to configure the look

Minimum number of connections: a database connection pool is kept, so if the amount of the application to the database is not connected, there will be a large number of database connection resources are wasted.
Maximum number of connections: is the maximum number of connection pools can apply, if the database connection requests exceeding the number of times, the database connection request later to be added to the waiting queue, which will affect the database operation after
the maximum idle time of
obtaining a connection timeout
retransmission timeout test connection times

#连接设置  这里面的名字,是DBCP数据源中定义好的
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&characterEncoding=utf8&useSSL=true
username=root
password=123456

#<!-- 初始化连接 -->
initialSize=10

#最大连接数量
maxActive=50

#<!-- 最大空闲连接 -->
maxIdle=20

#<!-- 最小空闲连接 -->
minIdle=5

#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60-->
maxWait=60000

#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;]
#注意:"user""password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=UTF8

#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true

#driver default 指定由连接池所创建的连接的只读(read-only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly=

#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_UNCOMMITTED

  • Then write a DBCP Tools
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUtils_DBCP {

    private static DataSource dataSource = null;

    static {
        try{
            InputStream in =  JdbcUtils_DBCP.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
            Properties properties = new Properties();
            properties.load(in);

            //创建数据源 工厂模式 --> 创建
            dataSource = BasicDataSourceFactory.createDataSource(properties);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取连接
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection(); //从数据源中获取连接
    }

    //释放连接资源
    public static void release(Connection conn, Statement st, ResultSet rs){
        if (rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (st!=null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

  • carry out testing
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;

public class TestDBCP {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement st = null;

        try {
            conn = JdbcUtils_DBCP.getConnection();
            // 区别
            // 使用? 占位符代替参数
            String sql = "insert into users(id,`NAME`,`PASSWORD`,`email`,`birthday`) values(?,?,?,?,?)";

            st = conn.prepareStatement(sql); //预编译SQL,先写sql,然后不执行

            // 手动给参数赋值
            st.setInt(1,4); //id
            st.setString(2,"qinjiang");
            st.setString(3,"1232112");
            st.setString(4,"[email protected]");
            // 注意点: sql.Date   数据库   java.sql.Date()
            //          util.Date  Java     new Date().getTime() 获得时间戳
            st.setDate(5,new java.sql.Date(new Date().getTime()));

            //执行
            int i = st.executeUpdate();
            if (i>0){
                System.out.println("插入成功!");
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils_DBCP.release(conn,st,null);
        }
    }
}

  • DBCP and C3P0 using similar methods, required jar package: c3p0-0.9.5.5, mchange-commons-java-0.2.19

  • Conclusion
    No matter what data source, the essence is still the same, DataSource interface will not change, the method will not become

Published 62 original articles · won praise 2 · Views 2735

Guess you like

Origin blog.csdn.net/nzzynl95_/article/details/104124777