当前位置:网站首页>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.properties
filedriver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false username = root password = 123456
Create a tool class
JdbcUtils
package 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_COMMITTED
Tool 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); } } }
边栏推荐
- Mysql - - Index
- For in, foreach, for of
- Link aggregation based on team mechanism
- Etcd 基于Raft的一致性保证
- Getting started with postman -- environment variables and global variables
- Recommendation of books related to strong foundation program mathematics
- jvm jni 及 pvm pybind11 大批量数据传输及优化
- Set, weakset, map, weakmap in ES6
- 浅议.NET遗留应用改造
- UI automation test: selenium+po mode +pytest+allure integration
猜你喜欢
Operate BOM objects (key)
Getting started with postman -- built-in dynamic parameters, custom parameters and assertions
2022 melting welding and thermal cutting examination materials and free melting welding and thermal cutting examination questions
Capture de paquets et tri du contenu externe - - autoresponder, composer, statistiques [3]
Inventory 2021 | yunyuansheng embracing the road
Pengcheng cup Web_ WP
Recommendation of books related to strong foundation program mathematics
SQL injection - Fundamentals of SQL database operation
Talk about daily newspaper design - how to write a daily newspaper and what is the use of a daily newspaper?
In 2021, the global foam protection packaging revenue was about $5286.7 million, and it is expected to reach $6615 million in 2028
随机推荐
JVM JNI and PVM pybind11 mass data transmission and optimization
APEC industry +: father of the king of the ox mill, industrial Internet "king of the ox mill anti-wear faction" Valentine's Day greetings | Asia Pacific Economic media | ChinaBrand
[Tang Laoshi] C -- encapsulation: member variables and access modifiers
一台服务器最大并发 tcp 连接数多少?65535?
Refer to some books for the distinction between blocking, non blocking and synchronous asynchronous
Use nodejs+express+mongodb to complete the data persistence project (with modified source code)
CesiumJS 2022^ 源码解读[7] - 3DTiles 的请求、加载处理流程解析
Visiontransformer (I) -- embedded patched and word embedded
Basic number theory -- Chinese remainder theorem
[secretly kill little buddy pytorch20 days -day02- example of image data modeling process]
Set, weakset, map, weakmap in ES6
Discussion Net legacy application transformation
MySQL——数据库备份
MySQL -- standardize database design
强化學習-學習筆記1 | 基礎概念
Interval product of zhinai sauce (prefix product + inverse element)
In 2021, the global foam protection packaging revenue was about $5286.7 million, and it is expected to reach $6615 million in 2028
18、 MySQL -- index
MDM mass data synchronization test verification
Service discovery and load balancing mechanism -service