当前位置:网站首页>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); } } }
边栏推荐
- 设计电商秒杀系统
- Single page application architecture
- Getting started with postman -- built-in dynamic parameters, custom parameters and assertions
- MySQL - SQL injection problem
- Talk about daily newspaper design - how to write a daily newspaper and what is the use of a daily newspaper?
- Advanced collaboration: coroutinecontext
- Nmap and masscan have their own advantages and disadvantages. The basic commands are often mixed to increase output
- Is flush account opening and registration safe and reliable? Is there any risk?
- Cesiumjs 2022 ^ source code interpretation [7] - Analysis of the request and loading process of 3dfiles
- MySQL——JDBC
猜你喜欢
Capturing and sorting out external articles -- autoresponder, composer, statistics [III]
Scientific research document management Zotero
"Actbert" Baidu & Sydney University of technology proposed actbert to learn the global and local video text representation, which is effective in five video text tasks
MySQL master-slave synchronization principle
MDM mass data synchronization test verification
Study diary: February 14th, 2022
Borui data and Sina Finance released the 2021 credit card industry development report
Viewing Chinese science and technology from the Winter Olympics (II): when snowmaking breakthrough is in progress
MySQL - database backup
Yyds dry goods inventory TCP & UDP
随机推荐
MySQL——规范数据库设计
Do you really know how old you are?
JS three families
"Actbert" Baidu & Sydney University of technology proposed actbert to learn the global and local video text representation, which is effective in five video text tasks
Refer to some books for the distinction between blocking, non blocking and synchronous asynchronous
The "boss management manual" that is wildly spread all over the network (turn)
17 websites for practicing automated testing. I'm sure you'll like them
[Yugong series] go teaching course 002 go language environment installation in July 2022
Monkey/ auto traverse test, integrate screen recording requirements
2022 high voltage electrician examination and high voltage electrician reexamination examination
Scientific research document management Zotero
jvm jni 及 pvm pybind11 大批量数据传输及优化
Borui data and Sina Finance released the 2021 credit card industry development report
同花顺开户注册安全靠谱吗?有没有风险的?
For in, foreach, for of
Is flush account opening and registration safe and reliable? Is there any risk?
Rhcsa third day notes
Rhcsa third day operation
强化學習-學習筆記1 | 基礎概念
Haven't expressed the artifact yet? Valentine's Day is coming. Please send her a special gift~