当前位置:网站首页>JDBC tutorial
JDBC tutorial
2022-07-02 23:36:00 【pengege666】
List of articles
JDBC Concept
1.1 JDBC Concept
JDBC Is the use of Java A set of language operation relational database API. Full name :( Java DataBase Connectivity ) Java Database connection .
1.2 JDBC The essence :
- official (sun company ) A set of rules defined to operate all relational databases , Interface
- Each database manufacturer to implement this set of interface , Provide database driver jar package
- We can use this interface (JDBC) Programming , The code that actually executes is the driver jar The implementation class in the package
1.3 Benefits of use
- Each database manufacturer uses the same interface ,Java The code does not need to be developed separately for different databases
- The underlying database can be replaced at any time , Access database Java The code is basically unchanged
JDBC introduction
Use steps
First step : To write Java Code
The second step :Java Code will SQL Send to MySQL Server side
The third step :MySQL The server receives SQL Statement and execute the SQL sentence
Step four : take SQL The result of statement execution is returned to Java Code
step1: Create a new empty project
Create a module
newly build lib package
step2: Import driver package
take mysql The driver package is placed under the module lib Catalog ( Name at will ) Next , And put the jar Add package as library file
take mysql-connector-java-5.1.48.jar Put it in lib Inside the directory ,Ctrl+V Put it in for
Make it effective
When adding as a library file , There are three options
- Global Library : Global availability
- Project Library : The project works
- Module Library : Module valid
step3: stay src Create a class
/** * JDBC Quick start */
public class JDBCDemo {
public static void main(String[] args) throws Exception {
//1. Registration drive
//Class.forName("com.mysql.jdbc.Driver");
//2. Get the connection
String url = "jdbc:mysql://127.0.0.1:3306/db1";
String username = "root";
String password = "12348765";
Connection conn = DriverManager.getConnection(url, username, password);
//3. Definition sql
String sql = "update account set money = 2000 where id = 1";
//4. Access to perform sql The object of Statement
Statement stmt = conn.createStatement();
//5. perform sql
int count = ((Statement) stmt).executeUpdate(sql);// Rows affected
//6. Processing results
System.out.println(count);
//7. Release resources
stmt.close();
conn.close();
}
}
JDBC API Detailed explanation
1.DriverManager
Registration drive
In the static code block in this class DriverManager Object's registerDriver() Method to register the driver , Then we just need to load Driver class , The static code block will execute . and Class.forName(“com.mysql.jdbc.Driver”); It can be loaded Driver class .
Be careful :
1.MySQL 5 Later driver package , You can omit the steps of registering the driver
2. Automatic loading jar In bag META-INF/services/java.sql.Driver Driver class in fileGet database connection
2.Connection
Connection( Database connection object ) effect :1. Access to perform SQL The object of 2. Manage affairs
- Access to perform SQL object
Common execution SQL object
Statement createStatement()
precompile SQL Implementation SQL object : prevent SQL Inject
PreparedStatement prepareStatement(sql)
The object that executes the stored procedure
CallableStatement prepareCall(sql)
- Business management
MySQL Operation of transaction management
Open transaction : BEGIN; perhaps START TRANSACTION;
Commit transaction : COMMIT;
Roll back the transaction : ROLLBACK;
JDBC Methods of transaction management
Open transaction
Commit transaction
Roll back the transaction
/** * JDBC API Detailed explanation :Connection */
public class JDBCDemo3_Connection {
public static void main(String[] args) throws Exception {
//1. Registration drive
//Class.forName("com.mysql.jdbc.Driver");
//2. Get the connection : If the connection is local mysql And the port is the default 3306 Can simplify writing
String url = "jdbc:mysql:///db1?useSSL=false";
String username = "root";
String password = "1234";
Connection conn = DriverManager.getConnection(url, username, password);
//3. Definition sql
String sql1 = "update account set money = 3000 where id = 1";
String sql2 = "update account set money = 3000 where id = 2";
//4. Access to perform sql The object of Statement
Statement stmt = conn.createStatement();
try {
// ============ Open transaction ==========
conn.setAutoCommit(false);
//5. perform sql
int count1 = stmt.executeUpdate(sql1);// Rows affected
//6. Processing results
System.out.println(count1);
int i = 3/0;
//5. perform sql
int count2 = stmt.executeUpdate(sql2);// Rows affected
//6. Processing results
System.out.println(count2);
// ============ Commit transaction ==========
// The program runs here , Indicates that there are no problems , Then you need to commit the transaction
conn.commit();
} catch (Exception e) {
// ============ Roll back the transaction ==========
// When an exception occurs, the program will execute to this place , At this point, the transaction needs to be rolled back
conn.rollback();
e.printStackTrace();
}
//7. Release resources
stmt.close();
conn.close();
}
}
3.Statement
/** * perform DML sentence * @throws Exception */
@Test
public void testDML() throws Exception {
//1. Registration drive
//Class.forName("com.mysql.jdbc.Driver");
//2. Get the connection : If the connection is local mysql And the port is the default 3306 Can simplify writing
String url = "jdbc:mysql:///db1?useSSL=false";
String username = "root";
String password = "1234";
Connection conn = DriverManager.getConnection(url, username, password);
//3. Definition sql
String sql = "update account set money = 3000 where id = 1";
//4. Access to perform sql The object of Statement
Statement stmt = conn.createStatement();
//5. perform sql
int count = stmt.executeUpdate(sql);// After execution DML sentence , Rows affected
//6. Processing results
//System.out.println(count);
if(count > 0){
System.out.println(" Modification successful ~");
}else{
System.out.println(" Modification failed ~");
}
//7. Release resources
stmt.close();
conn.close();
}
without junit If you depend , It can be run directly as a function or
4.ResultSet
ResultSet( Result set object ) effect : Encapsulates the SQL The result of the query statement .
And executed DQL Statement will return the object , Corresponding execution DQL The method of statement is as follows :
ResultSet executeQuery(sql): perform DQL sentence , return ResultSet object
that , We can traverse and view the contents of the result set .ResultSet Object provides methods to manipulate query result data .
boolean next()
explain :
Move the cursor forward one line from the current position
Judge whether the current line is a valid line
Method return value description :true : Effective navigation , There is data in the current row false : Invalid line , There is no data in the current row
xxx getXxx( Parameters ): get data
xxx : data type ; Such as : int getInt( Parameters ) ;String getString( Parameters )
Parameters : int Parameters of type : Number of columns , from 1 Start . String Parameters of type : Column name
/** * perform DQL * @throws Exception */
@Test
public void testResultSet() throws Exception {
//1. Registration drive
//Class.forName("com.mysql.jdbc.Driver");
//2. Get the connection : If the connection is local mysql And the port is the default 3306 Can simplify writing
String url = "jdbc:mysql:///db1?useSSL=false";
String username = "root";
String password = "1234";
Connection conn = DriverManager.getConnection(url, username, password);
//3. Definition sql
String sql = "select * from account";
//4. obtain statement object
Statement stmt = conn.createStatement();
//5. perform sql
ResultSet rs = stmt.executeQuery(sql);
//6. Processing results , Traverse rs All data in
/* // 6.1 Move the cursor down one line , And judge whether there is data in the current line while (rs.next()){ //6.2 get data getXxx() int id = rs.getInt(1); String name = rs.getString(2); double money = rs.getDouble(3); System.out.println(id); System.out.println(name); System.out.println(money); System.out.println("--------------"); }*/
// 6.1 Move the cursor down one line , And judge whether there is data in the current line
while (rs.next()){
//6.2 get data getXxx()
int id = rs.getInt("id");
String name = rs.getString("name");
double money = rs.getDouble("money");
System.out.println(id);
System.out.println(name);
System.out.println(money);
System.out.println("--------------");
}
//7. Release resources
rs.close();
stmt.close();
conn.close();
}
5.PreparedStatement
PreparedStatement effect : precompile SQL Statement and execute : The prevention of SQL Injection problem
SQL Injection concept : Modify pre-defined by operating input SQL sentence , The method used to execute code to attack the server .
PreparedStatement The function is to precompile SQL Statement and execute , So as to prevent SQL Injection problem .
public class JDBCDemo_Statement {
private static void testDML() throws Exception {
//1. Registration drive
//Class.forName("com.mysql.jdbc.Driver");
//2. Get the connection : If the connection is local mysql And the port is the default 3306 Can simplify writing
String url = "jdbc:mysql:///db1?useSSL=false";
String username = "root";
String password = "12348765";
Connection conn = DriverManager.getConnection(url, username, password);
//3. Definition sql
String sql = "select * from tb_user where username = ? and password = ?";
//4. obtain pstmt object
PreparedStatement pstmt = conn.prepareStatement(sql);
String name="zhangsan";
String pwd="123";
// Set up ? Value
pstmt.setString(1,name);
pstmt.setString(2,pwd);
//5. perform sql
ResultSet rs = pstmt.executeQuery();
//6. Processing results , Traverse rs All data in
// 6.1 Move the cursor down one line , And judge whether there is data in the current line
if (rs.next()){
System.out.println("OKKK!");
}else{
System.out.println("Error!");
}
}
public static void main(String[] args) throws Exception {
testDML();
}
}
In obtaining PreparedStatement Object time , take sql The statement is sent to mysql The server checks , compile ( These steps are time-consuming )
You don't have to do these steps when executing , Faster
If sql It's like a template , You only need to check once 、 compile
Database connection pool
Concept
Concept : Database connection pool is a container , To be responsible for the distribution of 、 Manage database connections (Connection). It allows applications to reuse an existing database connection , Instead of building a new . Release database connection with idle time exceeding the maximum idle time to avoid missing database connection caused by no free database connection
benefits : 1. Resource reuse 2. Improve system response speed 3. Avoid missing database connections
Realization
Database connection pool implementation
Standard interface :DataSource
official (SUN) Database connection pool standard interface provided , This interface is implemented by a third-party organization . This interface provides the function of obtaining connection :
Connection getConnection()
Common database connection pool
DBCP C3P0 DruidWe use Druid,Druid Connection pool is an open source database connection pool project of Alibaba . Powerful , Excellent performance , yes Java One of the best database connection pools in language
Driud Use steps
1. Import jar package druid-1.1.12.jar
2. Define configuration file
3. Load profile
4. Get database connection pool object
5. Get the connection
download druid Of jar package : Database connection pool druid Of jar Download from Bao official website - Download the latest version
When adding as a library file , There are three options
- Global Library : Global availability
- Project Library : The project works
- Module Library : Module valid
Selection module is valid
New file DruidDemo
druid.properties
The contents of the configuration file are as follows :
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///db1?useSSL=false&useServerPrepStmts=true
username=root
password=1234
# Initialize the number of connections
initialSize=5
# maximum connection
maxActive=10
# Maximum waiting time
maxWait=3000
DruidDemo.java
/** * Druid Database connection pool demo */
public class DruidDemo {
public static void main(String[] args) throws Exception {
//1. Import jar package
//2. Define configuration file
//3. Load profile
Properties prop = new Properties();
prop.load(new FileInputStream("jdbc-demo/src/druid.properties"));
//4. Get connection pool object
DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
//5. Get database connection Connection
Connection connection = dataSource.getConnection();
System.out.println(connection); // After obtaining the connection, you can continue to do other operations
//System.out.println(System.getProperty("user.dir"));
}
}
Last , Thank you very much JavaWebNotes Careful arrangement of articles !
边栏推荐
- @BindsInstance在Dagger2中怎么使用
- CDN acceleration requires the domain name to be filed first
- Maybe you read a fake Tianlong eight
- RuntimeError: no valid convolution algorithms available in CuDNN
- [redis notes] compressed list (ziplist)
- Detailed explanation of 'viewpager' in compose | developer said · dtalk
- C MVC creates a view to get rid of the influence of layout
- Brief introduction to common sense of Zhongtai
- Go basic anonymous variable
- 数据集-故障诊断:西储大学轴承的各项数据以及数据说明
猜你喜欢
Win11自动关机设置在哪?Win11设置自动关机的两种方法
采用VNC Viewer方式遠程連接樹莓派
CADD课程学习(4)-- 获取没有晶体结构的蛋白(SWISS-Model)
What if win11 can't turn off the sticky key? The sticky key is cancelled but it doesn't work. How to solve it
Go project operation method
List of major chip Enterprises
公司里只有一个测试是什么体验?听听他们怎么说吧
Deep analysis of data storage in memory - C language
What is the official website address of e-mail? Explanation of the login entry of the official website address of enterprise e-mail
Convolution和Batch normalization的融合
随机推荐
Markdown basic grammar
Pandora IOT development board learning (HAL Library) - Experiment 4 serial port communication experiment (learning notes)
简述中台的常识
php 获取真实ip
What experience is there only one test in the company? Listen to what they say
[ml] Li Hongyi III: gradient descent & Classification (Gaussian distribution)
MySQL基础
返回二叉树两个节点间的最大距离
Three solutions to frequent sticking and no response of explorer in win11 system
PHP get real IP
LINQ usage collection in C #
开发知识点
PR FAQ, what about PR preview video card?
[analysis of STL source code] imitation function (to be supplemented)
[array] binary search
Writing of head and bottom components of non routing components
Convolution和Batch normalization的融合
CDN acceleration requires the domain name to be filed first
All things work together, and I will review oceanbase's practice in government and enterprise industry
【Proteus仿真】51单片机+LCD12864推箱子游戏