当前位置:网站首页>JDBC -- use JDBC connection to operate MySQL database
JDBC -- use JDBC connection to operate MySQL database
2022-07-05 12:33:00 【It Chunhe】
Catalog
3.1. DriverManager: Drive management objects
3.3. Statement: perform sql The object of
3.4. ResultSet: Result set object , Encapsulate query results
3.5. PreparedStatement: perform sql The object of
4、 Use jdbc Operate the addition, deletion, modification and query of the database
4.2、 Modify the data in the database
1、what is JDBC?
JDBC The full name is :Java DataBase Connectivity
Java Database connection , Java Language operation database
JDBC The essence : Actually, it's official (sun company ) Defined A set of rules that 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 .
JDBC It's the interface , and JDBC The driver is the implementation of the interface , Database connection cannot be completed without driver ! Each database vendor has its own driver , To connect to your company's database .
2、jdbc Quick start
jdbc The use of is actually quite simple. We only need a few simple steps to add, delete, modify and query the database
Development steps :
【1】 Import driver jar package ( See what you installed on this machine mysql Import the corresponding version of the driver jar)
【2】 Registration drive
【3】 Get database connection object
【4】dingyisql
【5】 Access to perform sql Object of statement statement
【6】 perform sql
【7】 Processing results
【8】 Release resources
I'm using idea development tool , Create a module choice java project
Create a new folder lib take mysql The driver jar Package is copied to the lib in
Choose lib Right click Click on add as library take jar Add to dependency
mysql Driver download address :
link :https://pan.baidu.com/s/1mZNEKiPwO7ZhqjmcaY0OFQ
Extraction code :itch
quickstart Use jdbc Query data
package com.zhou.jdbc;
import java.sql.*;
public class Jdbc_quickstart {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// 1、 Registration drive
Class.forName("com.mysql.jdbc.Driver");
// 2、 Get database connection object
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day10","root","123456");
// 3、 Definition sql
String sql = "select * from person";
// 4、 Access to perform sql The object of
Statement stmt = conn.createStatement();
// 5、 perform sql
ResultSet rs = stmt.executeQuery(sql);
// 6、 Processing results
while (rs.next()){
// get data Two ways Get according to the index of the column Get... By column name
int id = rs.getInt(1);
String name = rs.getString("name");
String email = rs.getString("email");
// Print data
System.out.println(id + "----" + name + "----" + email);
}
// 7、 close resource
rs.close();
stmt.close();
conn.close();
}
}
3、jdbc Detailed explanation
3.1. DriverManager: Drive management objects
* function :
1. Registration drive : Tell the program which database driver to use jar
static void registerDriver(Driver driver) : Register with given driver DriverManager .
Write code using : Class.forName("com.mysql.jdbc.Driver");
Discover by looking at the source code : stay com.mysql.jdbc.Driver Class has static code blocks
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}Be careful :mysql5 After the drive jar Packages can omit the steps of registering drivers .
3.2. Get database connection
Method :static Connection getConnection(String url, String user, String password)
Parameters :
url: Specify the path of the connection
grammar :jdbc:mysql://ip Address ( domain name ): Port number / Database name
Example :jdbc:mysql://localhost:3306/db3
details : If the connection is local mysql The server , also mysql The default port for the service is 3306, be url I could just write it as :jdbc:mysql:/// Database name
user: user name
password: password
Connection: Database connection object
1. function :
1. Access to perform sql The object of
Statement createStatement()
PreparedStatement prepareStatement(String sql)
2. Manage affairs :
Open transaction :setAutoCommit(boolean autoCommit) : Call this method to set the parameter to false, That is, start the transaction
Commit transaction :commit()
Roll back the transaction :rollback()
3.3. Statement: perform sql The object of
1. perform sql
1. boolean execute(String sql) : You can do whatever you want sql understand
2. int executeUpdate(String sql) : perform DML(insert、update、delete) sentence 、DDL(create,alter、drop) sentence
* Return value : Number of rows affected , It can be judged by the number of rows affected DML Is the statement executed successfully Return value >0 Then the execution is successful , conversely , The failure .
3. ResultSet executeQuery(String sql) : perform DQL(select) sentence
3.4. ResultSet: Result set object , Encapsulate query results
boolean next(): Move the cursor down one line , Determine whether the current line is the end of the last line ( Is there any data ), If it is , Then return to false, If not, return true
getXxx( Parameters ): get data
Xxx: Representative data type Such as : int getInt() , String getString()
Parameters :
1. int: Represents the number of the column , from 1 Start Such as : getString(1)
2. String: Name of representative column . Such as : getString("name")
Be careful :
Use steps :
1. Move the cursor down one line
2. Judge whether there is data
3. get data
Sample code :
// Loop to determine whether the cursor is at the end of the last line .
while(rs.next()){
// get data
//6.2 get data
int id = rs.getInt(1);
String name = rs.getString("name");
double balance = rs.getDouble(3);
System.out.println(id + "---" + name + "---" + balance);
}
3.5. PreparedStatement: perform sql The object of
1. SQL Injection problem : In splicing sql when , Somewhat sql Special keywords participate in string splicing . Can cause security problems
1. Input users casually , Input password :a' or 'a' = 'a
2. sql:select * from user where username = 'fhdsjkf' and password = 'a' or 'a' = 'a'2. solve sql Injection problem : Use PreparedStatement Object to solve
3. precompiled SQL: Parameters use ? As placeholder
4. step :
1. Import driver jar package mysql-connector-java-5.1.37-bin.jar
2. Registration drive
3. Get database connection object Connection
4. Definition sql
* Be careful :sql Parameter usage of ? As placeholder . Such as :select * from user where username = ? and password = ?;
5. Access to perform sql Object of statement PreparedStatement Connection.prepareStatement(String sql)
6. to ? assignment :
* Method : setXxx( Parameters 1, Parameters 2)
* Parameters 1:? Location number of from 1 Start
* Parameters 2:? Value
7. perform sql, Accept the return result , There is no need to pass on sql sentence
8. Processing results
9. Release resourcesIt will be used later PreparedStatement To complete all operations of addition, deletion, modification and query
1. Can prevent SQL Inject
2. More efficient
4、 Use jdbc Operate the addition, deletion, modification and query of the database
4.1、 Add data to the database
package com.zhou.jdbc;
import java.sql.*;
public class Jdbc_insert {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// 1、 Registration drive
Class.forName("com.mysql.jdbc.Driver");
// 2、 Get database connection object
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day10", "root", "123456");
// 3、 Definition sql
String sql = "insert into person values(null,?,?,?)";
// 4、 Access to perform sql The object of Precompiled only sql
PreparedStatement pstmt = conn.prepareStatement(sql);
// 5、 Assign parameters
pstmt.setString(1, " Jay Chou ");
pstmt.setString(2, "[email protected]");
pstmt.setString(3, " Taipei ");
// 6、 perform sql
int i = pstmt.executeUpdate();
// 7、 Number of lines affected by printing
System.out.println(i);
// 8、 close resource
pstmt.close();
conn.close();
}
}
4.2、 Modify the data in the database
// 1、 Registration drive
Class.forName("com.mysql.jdbc.Driver");
// 2、 Get database connection object
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/day10", "root", "123456");
// 3、 Definition sql
String sql = "update person set name = 'zhoujielun' where id = ?"; // Change Jay Chou to zhoujielun
// 4、 Access to perform sql The object of Precompiled only sql
PreparedStatement pstmt = conn.prepareStatement(sql);
// 5、 Assign parameters
pstmt.setInt(1,10);
// 6、 perform sql
int i = pstmt.executeUpdate();
// 7、 Number of lines affected by printing
System.out.println(i);
// Judge
if (i > 0){
System.out.println(" Modification successful !");
}else {
System.out.println(" Modification failed !");
}
// 8、 close resource
pstmt.close();
conn.close();
4.3、 Delete data
Put... In the code above sql Statement changes :
// 3、 Definition sql String sql = "delete from person where id = ?";
边栏推荐
- Semantic segmentation experiment: UNET network /msrc2 dataset
- Pytoch loads the initialization V3 pre training model and reports an error
- Leetcode-1. Sum of two numbers (Application of hash table)
- 7月华清学习-1
- Get data from the database when using JMeter for database assertion
- Deep discussion on the decoding of sent protocol
- Seven polymorphisms
- Learning JVM garbage collection 06 - memory set and card table (hotspot)
- Simple production of wechat applet cloud development authorization login
- GPS數據格式轉換[通俗易懂]
猜你喜欢
Get the variable address of structure member in C language
NPM install reports an error
16 channel water lamp experiment based on Proteus (assembly language)
Third party payment interface design
Select drop-down box realizes three-level linkage of provinces and cities in China
ZABBIX customized monitoring disk IO performance
Two minutes will take you to quickly master the project structure, resources, dependencies and localization of flutter
强化学习-学习笔记3 | 策略学习
Understand kotlin from the perspective of an architect
Embedded software architecture design - message interaction
随机推荐
PIP command reports an error pip is configured with locations that requires tls/ssl problems
手机 CPU 架构类型了解
Complete activity switching according to sliding
How to design an interface?
Pytoch monolayer bidirectional_ LSTM implements MNIST and fashionmnist data classification
Summary of C language learning problems (VS)
Matlab label2idx function (convert the label matrix into a cell array with linear index)
Embedded software architecture design - message interaction
Solve the error 1045 of Navicat creating local connection -access denied for user [email protected] (using password
Get the variable address of structure member in C language
MySQL trigger
Interviewer: is acid fully guaranteed for redis transactions?
Just a coincidence? The mysterious technology of apple ios16 is actually the same as that of Chinese enterprises five years ago!
Intern position selection and simplified career development planning in Internet companies
SENT协议译码的深入探讨
How does MySQL execute an SQL statement?
MySQL view
[figure neural network] GNN from entry to mastery
Why do you always fail in automated tests?
Array cyclic shift problem