当前位置:网站首页>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); } } }
边栏推荐
- In 2021, the global revenue of thick film resistors was about $1537.3 million, and it is expected to reach $2118.7 million in 2028
- Qualcomm platform WiFi -- P2P issue
- Kubernetes 通信异常网络故障 解决思路
- Install and use Chrony, and then build your own time server
- In 2021, the global foam protection packaging revenue was about $5286.7 million, and it is expected to reach $6615 million in 2028
- 鹏城杯 WEB_WP
- Study diary: February 14th, 2022
- MDM mass data synchronization test verification
- MySQL——索引
- Redis data migration (II)
猜你喜欢

Borui data and Sina Finance released the 2021 credit card industry development report

How to choose cache read / write strategies in different business scenarios?

Day 9 HomeWrok-ClassHierarchyAnalysis

Getting started with postman -- built-in dynamic parameters, custom parameters and assertions
![[Tang Laoshi] C -- encapsulation: member variables and access modifiers](/img/be/0b38c0f1a27f819f7c79bcf634fbd4.jpg)
[Tang Laoshi] C -- encapsulation: member variables and access modifiers

Selenium has three waiting methods (forced waiting, implicit waiting, and display waiting)
![[secretly kill little buddy pytorch20 days -day02- example of image data modeling process]](/img/14/8ab1f1fb142e10dead124851180d03.jpg)
[secretly kill little buddy pytorch20 days -day02- example of image data modeling process]
![抓包整理外篇——————autoResponder、composer 、statistics [ 三]](/img/bf/ac3ba04c48e80b2d4f9c13894a4984.png)
抓包整理外篇——————autoResponder、composer 、statistics [ 三]

Mysql database ----- common commands of database (based on database)

你真的知道自己多大了吗?
随机推荐
Operate BOM objects (key)
18、 MySQL -- index
你真的知道自己多大了吗?
JS three families
Scientific research document management Zotero
Cannot load driver class: com. mysql. cj. jdbc. Driver
The global industrial design revenue in 2021 was about $44360 million, and it is expected to reach $62720 million in 2028. From 2022 to 2028, the CAGR was 5.5%
No matter how hot the metauniverse is, it cannot be separated from data
请教大家一个问题,用人用过flink sql的异步io关联MySQL中的维表吗?我按照官网设置了各种
The 12th Blue Bridge Cup
Rhcsa third day notes
MySQL - index
"Designer universe" APEC safety and health +: environmental protection Panda "xiaobaobao" Happy Valentine's Day 2022 | ChinaBrand | Asia Pacific Economic media
Single page application architecture
技术管理进阶——如何在面试中考察候选人并增大入职概率
JVM JNI and PVM pybind11 mass data transmission and optimization
Use nodejs+express+mongodb to complete the data persistence project (with modified source code)
Brief analysis of ref nerf
抓包整理外篇——————autoResponder、composer 、statistics [ 三]
Borui data and Sina Finance released the 2021 credit card industry development report