当前位置:网站首页>MySQL——JDBC
MySQL——JDBC
2022-07-03 21:11:00 【Can't learn java】
List of articles
1、 Database driven

- The program needs to be driven by database , Dealing with databases
2、JDBC
- SUN Companies to simplify the development of ( Unification of data ) operation , Provides a (Java Operating the database ) standard , Be commonly called JDBC
- For developers , Just master JDBC Interface operation
3、 first JDBC Program
Create test database
CREATE DATABASE `jdbcStudy` CHARACTER SET utf8 COLLATE utf8_general_ci; USE `jdbcStudy`; CREATE TABLE `users`( `id` INT PRIMARY KEY, `NAME` VARCHAR(40), `PASSWORD` VARCHAR(40), `email` VARCHAR(60), birthday DATE ); INSERT INTO `users`(`id`,`NAME`,`PASSWORD`,`email`,`birthday`) VALUES('1','zhangsan','123456','[email protected]','1980-12-04'), ('2','lisi','123456','[email protected]','1981-12-04'), ('3','wangwu','123456','[email protected]','1979-12-04')Import database driver

Write test code
package demo; import java.sql.*; // first JDBC Program public class JdbcFirstDemo { public static void main( String[] args ) throws ClassNotFoundException, SQLException { //1. The load driver Class.forName("com.mysql.jdbc.Driver"); // Fixed writing , The load driver //2. Connection information String url = "jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false"; String username = "root"; String password = "123456"; //3. Successful connection Database objects Connection On behalf of the database Connection connection = DriverManager.getConnection(url, username, password); //4. perform SQL The object of Statement perform sql The object of Statement statement = connection.createStatement(); //5. perform SQL The object of Go to perform SQL, There may be results , View return results String sql="SELECT * FROM users"; ResultSet resultSet = statement.executeQuery(sql); // Return result set , The result set encapsulates all the query results while (resultSet.next()){ System.out.println("id="+resultSet.getObject(1)); System.out.println("name="+resultSet.getObject(2)); System.out.println("pwd="+resultSet.getObject(3)); System.out.println("email="+resultSet.getObject(4)); System.out.println("birthday="+resultSet.getObject(5)); System.out.println("======================"); } //6. Release the connection resultSet.close(); statement.close(); connection.close(); } }
4、 Step summary
- The load driver
- Connect to database DriverManager
- Get executed sql The object of Statement
- Get the returned result set
5、JDBC Object interpretation
- Class.forName(“com.mysql.jdbc.Driver”); // The load driver
- connection: Database objects , Get a database
- statement: perform SQL sentence
- statement.executeQuery(sql) // Query statement , return ResultSet Result set
- statement.executeUpdate(sql) // UPDATE statement , Returns the number of updated rows
- statement.execute(sql) // whatever SQL sentence
- ResultSet: SQL Query result set , According to the type of database
- resultSet.next() // The pointer , Move to the next data
- resultSet.getInt( Parameters ); // Get integer data , It can be a subscript ( from 1 Start ), It can also be " Table field name "
- resultSet.getString( Parameters ); // Get string data , It can be a subscript ( from 1 Start ), It can also be " Table field name "
- resultSet.getObject( Parameters ); // Get arbitrary data , It can be a subscript ( from 1 Start ), It can also be " Table field name "
- Release resources :
- resultSet.close();
- statement.close();
- connection.close();
6、 Write tool class
stay src Create under directory
db.propertiesfiledriver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false username = root password = 123456Create a tool class
JdbcUtilspackage demo; import java.io.IOException; import java.io.InputStream; import java.sql.*; import java.util.Properties; public class JdbcUtils { private static String driver=null; private static String url=null; private static String username=null; private static String password=null; static { try{ InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties"); Properties properties = new Properties(); properties.load(in); driver= properties.getProperty("driver"); url= properties.getProperty("url"); username= properties.getProperty("username"); password= properties.getProperty("password"); // 1. The driver only loads once Class.forName(driver); }catch (IOException e){ } catch (ClassNotFoundException e) { e.printStackTrace(); } } // Get the connection public static Connection getConnection() throws SQLException { return DriverManager.getConnection(url, username, password); } // Release resources public static void release( Connection conn, Statement st,ResultSet rs ){ if(rs!=null){ try { rs.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(st!=null){ try { st.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(conn!=null){ try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } }Use tool class
package demo; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class TestInsert { public static void main( String[] args ) { Connection conn=null; Statement st=null; ResultSet rs=null; try { conn = JdbcUtils.getConnection();// Get database connection st = conn.createStatement(); // get SQL Execution object of String sql="INSERT\tINTO users(`id`,`NAME`,`PASSWORD`,`email`,`birthday`) " + "VALUES(4,'Java be unable to learn how to do sth. ','123456','[email protected]','2022-07-02')"; int i = st.executeUpdate(sql); if(i>0){ System.out.println(" Insert the success "); } } catch (SQLException throwables) { throwables.printStackTrace(); } finally { JdbcUtils.release(conn,st,rs); } } }
7、JDBC Operational transaction
7.1、 Create table
-- Create a user table
create table account(
id int primary key auto_increment,
name varchar(40),
money float
);
-- insert data
insert into account(name,money) values ('A',1000);
insert into account(name,money) values ('B',1000);
insert into account(name,money) values ('C',1000);
7.2、 Business
Either they all succeed , Or they all failed
ACID principle :
- Atomicity : All or nothing , All or nothing
- Uniformity : The total remains unchanged
- Isolation, : Multiple threads do not interfere with each other
- Dirty reading : One transaction reads another transaction that is not committed
- It can't be read repeatedly : In the same business , Repeatedly read the data in the table , Table data has changed
- Virtual reading ( Fantasy reading ): In a business , Read the data inserted by others , It leads to inconsistent results before and after reading
- persistence : Once submitted, it's irreversible , Persist to database
package demo01; import demo.JdbcUtils; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class TestTransaction01 { public static void main( String[] args ) { Connection conn=null; PreparedStatement st=null; ResultSet rs=null; try { conn = JdbcUtils.getConnection(); // Turn off automatic submission of the database , Automatically opens the transaction conn.setAutoCommit(false); String sql1="update account set money = money-100 where name ='A'"; st = conn.prepareStatement(sql1); st.execute(); int x = 1/0; // Report errors String sql2="update account set money = money+100 where name ='B'"; st = conn.prepareStatement(sql2); st.execute(); // Commit transaction conn.commit(); System.out.println(" Successful operation "); } catch (SQLException throwables) { try { conn.rollback(); // If it fails, roll back , Rollback by default } catch (SQLException e) { e.printStackTrace(); } } finally { JdbcUtils.release(conn,st,rs); } } }
7.3、 summary
- Start business : conn.setAutoCommit(false);
- A set of business execution completed , Commit transaction
- Can be in catch The definition shown in the statement , Rollback statement , By default, failure rolls back
8、 Database connection pool
- Database connection —— completion of enforcement —— Release
- Connect —— It is a waste of system resources
- Pool technology : Prepare some resources in advance , Come and connect with the prepared
- Minimum connections
- maximum connection
- Waiting for timeout
- Write connection pools , Implement an interface DataSource
- Open source data source implementation
- DBCP
- C3P0
- Druid
- Only , In project development, there is no need to write code to connect to the database
8.1 、DBCP:
establish dbcpconfig.properties file
# connections setting up The nouns in this , yes DBCP Defined in the data source driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/jdbcstudy?userUnicode=true&characterEncoding=utf8&useSSL=false username=root password=123456 #<!-- Initialize connection --> initialSize=10 # Maximum number of connections maxActive=50 #<!-- Maximum free connection --> maxIdle=20 #<!-- Minimum free connection --> minIdle=5 #<!-- Timeout wait time in milliseconds 6000 millisecond /1000 be equal to 60 second --> maxWait=60000 #JDBC The format of the connection attribute attribute attached to the driver when establishing the connection must be as follows :【 Property name =property;】 # Be careful :"user" And "password" Two attributes are explicitly passed , So there's no need to include them . connectionProperties=useUnicode=true;characterEncoding=utf8 # Specifies the automatic commit of connections created by the connection pool (auto-commit) state . defaultAutoCommit=true #driver default Specifies the read-only... Of the connection created by the connection pool (read-only) state . # If the value is not set , be “setReadOnly” Method will not be called .( Some drivers do not support read-only mode , Such as :Informix) defaultReadOnly= #driver default Specify the transaction level of the connection created by the connection pool (TransactionIsolation). # The available values are one of the following :( Details visible javadoc.)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE defaultTransactionIsolation=READ_COMMITTEDTool class
package demo02; import demo.JdbcUtils; import org.apache.commons.dbcp2.BasicDataSource; import org.apache.commons.dbcp2.BasicDataSourceFactory; import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public class JdbcUtils_DBCP { private static BasicDataSource dataSource = null; static { try{ InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties"); Properties properties = new Properties(); properties.load(in); // create data source Factory mode --> Create objects dataSource = BasicDataSourceFactory.createDataSource(properties); }catch (Exception e){ } } // Get the connection public static Connection getConnection() throws SQLException { return dataSource.getConnection(); // Get the connection from the data source } // Release resources public static void release( Connection conn, Statement st, ResultSet rs ){ if(rs!=null){ try { rs.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(st!=null){ try { st.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(conn!=null){ try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } }Test code
package demo02; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class TestDBCP { public static void main( String[] args ) { Connection conn=null; Statement st=null; ResultSet rs=null; try { conn = JdbcUtils_DBCP.getConnection();// Get database connection st = conn.createStatement(); // get SQL Execution object of String sql="INSERT INTO users(`id`,`NAME`,`PASSWORD`,`email`,`birthday`) " + "VALUES(6,'JavaStudy','123456','[email protected]','2022-07-02')"; int i = st.executeUpdate(sql); if(i>0){ System.out.println(" Insert the success "); } } catch (SQLException throwables) { throwables.printStackTrace(); } finally { JdbcUtils_DBCP.release(conn,st,null); } } }
8.2、c3p0
establish c3p0-config.xml file
<?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcstudy?userUnicode=true&characterEncoding=utf8&useSSL=false&</property> <property name="user">root</property> <property name="password">123456</property> <property name="acquiredIncrement">5</property> <property name="initialPoolSize">10</property> <property name="minPoolSize">5</property> <property name="maxPoolSize">20</property> </default-config> <name-config name="MySQL"> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcstudy?userUnicode=true&characterEncoding=utf8&useSSL=false&</property> <property name="user">root</property> <property name="password">123456</property> <property name="acquiredIncrement">5</property> <property name="initialPoolSize">10</property> <property name="minPoolSize">5</property> <property name="maxPoolSize">20</property> </name-config> </c3p0-config>Tool class :
package demo02; import com.mchange.v2.c3p0.ComboPooledDataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JdbcUtils_c3p0 { private static ComboPooledDataSource dataSource = null; static { try{ // create data source Factory mode --> Create objects dataSource = new ComboPooledDataSource(); }catch (Exception e){ } } // Get the connection public static Connection getConnection() throws SQLException { return dataSource.getConnection(); // Get the connection from the data source } // Release resources public static void release( Connection conn, Statement st, ResultSet rs ){ if(rs!=null){ try { rs.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(st!=null){ try { st.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if(conn!=null){ try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } }Test code :
package demo02; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class Testc3p0 { public static void main( String[] args ) { Connection conn=null; Statement st=null; ResultSet rs=null; try { conn = JdbcUtils_c3p0.getConnection();// Get database connection st = conn.createStatement(); // get SQL Execution object of String sql="INSERT INTO users(`id`,`NAME`,`PASSWORD`,`email`,`birthday`) " + "VALUES(10,'JavaStudy','123456','[email protected]','2022-07-02')"; int i = st.executeUpdate(sql); if(i>0){ System.out.println(" Insert the success "); } } catch (SQLException throwables) { throwables.printStackTrace(); } finally { JdbcUtils_DBCP.release(conn,st,null); } } }
边栏推荐
- Design e-commerce seckill system
- Basic knowledge of dictionaries and collections
- How to handle wechat circle of friends marketing activities and share production and release skills
- Etcd 基于Raft的一致性保证
- 【愚公系列】2022年7月 Go教学课程 002-Go语言环境安装
- Single page application architecture
- Borui data and Sina Finance released the 2021 credit card industry development report
- Kubernetes 通信异常网络故障 解决思路
- Line segment tree blue book explanation + classic example acwing 1275 Maximum number
- From the behind the scenes arena of the ice and snow event, see how digital builders can ensure large-scale events
猜你喜欢

No matter how hot the metauniverse is, it cannot be separated from data

Qt6 QML Book/Qt Quick 3D/基础知识

@Transactional注解失效的场景

MySQL——数据库备份

2022 low voltage electrician examination and low voltage electrician simulation examination question bank

leetcode-540. A single element in an ordered array

Leetcode daily question 540 A single element in an ordered array Valentine's Day special article looking for a single dog in a pile of lovers ~ the clown is myself

Software testing skills, JMeter stress testing tutorial, obtaining post request data in x-www-form-urlencoded format (24)

Baohong industry | good habits that Internet finance needs to develop

Haven't expressed the artifact yet? Valentine's Day is coming. Please send her a special gift~
随机推荐
Memory analyzer (MAT)
MySQL——SQL注入问题
XAI+网络安全?布兰登大学等最新《可解释人工智能在网络安全应用》综述,33页pdf阐述其现状、挑战、开放问题和未来方向
How to handle wechat circle of friends marketing activities and share production and release skills
MySQL——规范数据库设计
Offset related concepts + drag modal box case
"Designer universe" APEC safety and health +: environmental protection Panda "xiaobaobao" Happy Valentine's Day 2022 | ChinaBrand | Asia Pacific Economic media
阻塞非阻塞和同步异步的区分 参考一些书籍
Do you really know how old you are?
Reinforcement learning - learning notes 1 | basic concepts
Leetcode daily question 540 A single element in an ordered array Valentine's Day special article looking for a single dog in a pile of lovers ~ the clown is myself
Such as the visual appeal of the live broadcast of NBA Finals, can you still see it like this?
Recommendation of books related to strong foundation program mathematics
电子科技大学|强化学习中有效利用的聚类经验回放
Pengcheng cup Web_ WP
MySQL——数据库备份
MySQL - SQL injection problem
SQL injection - Fundamentals of SQL database operation
Brief analysis of ref nerf
Strange way of expressing integers (expanding Chinese remainder theorem)