当前位置:网站首页>Summer 2022 software innovation laboratory training JDBC
Summer 2022 software innovation laboratory training JDBC
2022-07-29 10:27:00 【Flying dinosaur】
List of articles
Use JDBC Preparation
- The database connection driver corresponding to the database version jar package , Download link , For example, my database version 8.0.25, So I should download 8.0.25 Connect packets

MySQL database , It is recommended to install the database
MySQL 8, becauseMySQL 5There seemed to be some problems when I was a sophomoreCreate a database according to your preferences , You can operate it manually during class , The database I created is like this

JDBC Brief introduction
JDBC(Java DataBase Connectivity) yes Java Language used to regulate how the client program to access the database application program interface , Provides such as queries 、 to update ( Additions and deletions ) Method of data in database .JDBC, yes Sun The company provides a set of Interface ,java Programmers only need Programming for this set of interfaces . Different database vendors , We need to focus on this set of interfaces , Provide different implementations . A collection of different implementations , It is the driver of different databases . Make an inappropriate analogy , You should use different methods to use , Refer to the figure below , The following figure is from the blog

How to use JDBC?
got it JDBC What is it? , Why is there JDBC after , We need to learn to use JDBC.
1. Download the driver package
At the beginning of this blog , Let's download the driver package corresponding to the database , Because my database is MySQL 8.0.25, So the data package I downloaded is MySQL 8.0.25 Driver package , As shown in the figure

2. establish lib Catalog
After preparing the database driver package , We are going to create an ordinary Java project , What I use here is IDEA Enterprise Edition , Don't put the screenshot after the creation . Then we need to create one under the project folder lib Catalog , there lib The directory is dedicated to Java A series of bags , Like this time we went to JDBC, So here we are lib The directory stores MySQL Drive pack .

3. Unzip the driver package , Import driver jar package
After creation lib After the catalog , We need to unzip the driver package , After decompression, we can see the following content ( Only aim at MySQL 8.0.25 Drive pack )

The only thing we need is inside mysql-connector-java-8.0.25.jar, Copy and paste this package into the newly created lib Catalog , Right click under the directory jar package ——> Add as library , As shown in the figure

Then directly determine

4. Use Java The code is right MySQL Database operation
load
MySQLdriveClass.forName("com.mysql.cj.jdbc.Driver");Get database connection
// obtain mysql Connection address String strURL = "jdbc:mysql://localhost:3306/ Database name ?&useSSL=false&serverTimezone=UTC"; // User name String username = "root"; // User password String password = "123456"; Connection con = DriverManager.getConnection(strURL, username, password);establish
statementobject , In order to preventSQLStatement Injection , We'll use itPreparedStatementTo preprocess// establish statement Class object , Used to perform SQL sentence ! Statement stm = con.createStatement();When we get
stmObject can then be used to operatemysqlsentence , Add, delete, change and query databaseunderstand
StatementObject to perform SQL Method of statement// adopt SQL Inquire about , Return the query result to Result The result set ResultSet rs = st.executeQuery(sql); // adopt SQL Update database content , Return the number of affected rows int i = st.executeUpdate(sql);After the database operation is finished , Need to be closed
ResultSet、Statement、ConnectionWe need to know after operating the database
ResultSet、Statement、ConnectionIt takes up memory in the program , So we need to close , And we need to pay attention to the closing sequence , It's from left to right .The first is the simplest shutdown method , Close directly after the operation
rs.close(); st.close(); con.close();But we can also change our thinking , Encapsulate the database shutdown operation directly into a method, like the following .
// Close database connection public static void release(Connection con, Statement st, ResultSet rs) { boolean flag = true; if (rs != null) { try { rs.close(); rs = null; } catch (SQLException e) { e.printStackTrace(); flag = false; } } if (st != null) { try { st.close(); st = null; } catch (SQLException e) { e.printStackTrace(); flag = false; } } if (con != null) { try { con.close(); con = null; } catch (SQLException e) { e.printStackTrace(); flag = false; } } }In the following , We will make a database operation class by ourselves , To encapsulate some simple operations of the database , For example, database connection 、 Database shutdown or other database operations ( Database query and update )
Simple practice
Query operation
// Defining variables
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
// Load database driver com.mysql.cj.jdbc.Driver
String strDriver = "com.mysql.cj.jdbc.Driver";
// obtain mysql Connection address
String strURL = "jdbc:mysql://localhost:3306/market?&useSSL=false&serverTimezone=UTC";
// Database user name
String username = "root";
// Database user password
String password = "123456";
// Load database driver
Class.forName(strDriver);
System.out.println(" Load database driver ");
// Get database connection
con = DriverManager.getConnection(strURL, username, password);
System.out.println(" Database connection successful ");
// obtain Statement object , To operate on database statements
st = con.createStatement();
String sql = "SELECT * FROM book";
// adopt SQL Inquire about , Put the query results into Result The results are concentrated
rs = st.executeQuery(sql);
// Use next To traverse the data result set , And output
while (rs.next()) {
int id = rs.getInt(1);
String name = rs.getString(2);
double price = rs.getDouble(3);
System.out.println(id + " " + name + " " + price);
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
} finally {
// Close result set ResultSet
if (rs != null) {
try {
rs.close();
System.out.println("ResultSet Successfully closed ");
} catch (SQLException e) {
e.printStackTrace();
}
}
// Close the operation object Statement
if (st != null) {
try {
st.close();
System.out.println("Statement Successfully closed ");
} catch (SQLException e) {
e.printStackTrace();
}
}
// Close the database connection object Connection
if (con != null) {
try {
con.close();
System.out.println("Connection Successfully closed ");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
The above example is only a query operation for the database , In many cases, we need more than just query , It is the update operation of the database , For example, add, delete, and modify .
1. Add operation
Here I want to insert a new database data , Number 6, Book name Criminal suspect X The dedication of , Price 43, In the database SQL The statement is as follows :
INSERT INTO book VALUES(6, " Criminal suspect X The dedication of ", 43);
therefore , We just need to simply modify the... In the example 24~33 A line of code will do
String sql = "INSERT INTO book VALUES(6, ' Criminal suspect X The dedication of ', 43)";
int i = st.executeUpdate(sql);
// Judge whether the number of affected rows is 0, if 0, Then the update operation just now did not succeed , If it is not 0, be SQL Statement operation succeeded
if (i != 0) {
System.out.println(" Insert the success !");
} else {
System.out.println(" Insert the failure !");
}
As a result, this data was successfully inserted

view the database

2. Delete operation
Here we assume that we need to delete the data just now , database SQL The statement is
DELETE FROM book WHERE bid = 6;
Because the delete operation belongs to the database update operation , So just change one of them String Variables
String sql = "DELETE FROM book WHERE bid = 6";
The final result was successfully deleted , As shown in the figure

3. Change operation
Here, if I want to modify the 5 Record price , database SQL The sentence of is
UPDATE book SET bprice = 20 WHERE bid = 5;
Here we only need to modify String Variables
String sql = "UPDATE book SET bprice = 20 WHERE bid = 5";
The final result is modified successfully , As shown in the figure

PreparedStatement Use
Actually in PreparedStatement Use , Follow Statement The use of is almost the same , It's just PreparedStatement A little more steps , Here's the code , You can compare it with Statement The difference in the use of
// Defining variables
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
// Load database driver com.mysql.cj.jdbc.Driver
String strDriver = "com.mysql.cj.jdbc.Driver";
// obtain mysql Connection address
String strURL = "jdbc:mysql://localhost:3306/market?&useSSL=false&serverTimezone=UTC";
// Database user name
String username = "root";
// Database user password
String password = "123456";
// Load database driver
Class.forName(strDriver);
System.out.println(" Load database driver ");
// Get database connection
con = DriverManager.getConnection(strURL, username, password);
System.out.println(" Database connection successful ");
// Database operation statement , The question mark here is the parameter we need to set ourselves
String sql = "SELECT * FROM book WHERE bid = ?";
// SQL Statement preprocessing , obtain PreparedStatement object
pst = con.prepareStatement(sql);
// by SQL Statement setting parameters , here setObject() The first parameter in the method represents SQL The question marks in the statement , The second parameter represents the setting variable , For example, the number we need to query here is 1 Book information
pst.setObject(1, 1);
rs = pst.executeQuery();
while (rs.next()) {
int id = rs.getInt(1);
String name = rs.getString(2);
double price = rs.getDouble(3);
System.out.println(id + " " + name + " " + price);
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
} finally {
// Close result set ResultSet
if (rs != null) {
try {
rs.close();
System.out.println("ResultSet Successfully closed ");
} catch (SQLException e) {
e.printStackTrace();
}
}
// Close the operation object Statement
if (pst != null) {
try {
pst.close();
System.out.println("Statement Successfully closed ");
} catch (SQLException e) {
e.printStackTrace();
}
}
// Close the database connection object Connection
if (con != null) {
try {
con.close();
System.out.println("Connection Successfully closed ");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
It should be noted here that I used the lazy method when setting parameters , That is to use pst.setObject(1, 1) The way , But in fact, we should use pst.setInt(1, 1) In a more accurate way , Because we need to see according to the specific database fields . In the future, we will use the general class of database operation , To connect data 、 close 、 update operation , So in fact, I will still use pst.setObject() Method to set parameters
Then according to the above code , Whether it can be analogized , How to use Preparedment Perform database operations ? The following is an example of deleting a data record , Other additions and modifications , Please also operate by yourselves
// Database operation statement , The question mark here is the parameter we need to set ourselves
String sql = "DELETE FROM book WHERE bid = ? AND bprice = ?";
// SQL Statement preprocessing , obtain PreparedStatement object
pst = con.prepareStatement(sql);
// by SQL Statement setting parameters , here setObject() The first parameter in the method represents SQL The question marks in the statement , The second parameter represents the setting variable , For example, the number we need to query here is 1 Book information
pst.setInt(1, 1);
// Because the book price field of the database I created is Double
pst.setDouble(2, 12);
int i = pst.executeUpdate();
if (i != 0) {
System.out.println(" success ");
} else {
System.out.println(" Failure ");
}
I don't know if you have any doubts here , Why Statement It also needs to be PreparedStatement?
Statement and PreparedStatement difference
Then we need to know the difference between the two , Reference blog
Performance aspect
Statementsentence// Get database connection con = DriverManager.getConnection(strURL, username, password); // obtain Statement object , To operate on database statements st = con.createStatement(); String sql = "SELECT * FROM book"; // adopt SQL Inquire about , Put the query results into Result The results are concentrated rs = st.executeQuery(sql);PreparedStatementsentence// Get database connection con = DriverManager.getConnection(strURL, username, password); // Database operation statement , The question mark here is the parameter we need to set ourselves String sql = "SELECT * FROM book WHERE bid = ?"; // SQL Statement preprocessing , obtain PreparedStatement object pst = con.prepareStatement(sql); // by SQL Statement setting parameters , here setObject() The first parameter in the method represents SQL The question marks in the statement , The second parameter represents the setting variable , For example, the number we need to query here is 1 Book information pst.setObject(1, 1); rs = pst.executeQuery();From the above comparison , We can see
PreparedStatementThere is a precompile process , And it's bound tosqlsentence , No matter how many times , Will not compile again . andStatementIs different ,sqlHow many times , How many times does it need to be compiled , thereforePreparedStatementMore efficient thanStatementhighConvenient for later changes , Improve code reading and maintainability
We can notice that
StatementThe database operation statement of is dead , It cannot be changed when the program is running , howeverPreparedStatementstay SQL The user-defined parameters required in the statement are all carried?Of , We need to passsetInt()、setObject()、setString()Wait for methods to set parameters , Easy to read and maintain the codeprevent SQL Inject
If you're using
StatementIn words , Want to query aIDbook , The statement reserved by the program is"SELECT * FROM book WHERE bid = " + bid, But if someone wants to know all the data at this time , Then he willbid = 2 OR 1 = 1, Finally formedSQLThe statement isSELECT * FROM book WHERE bid = 2 OR 1 = 1, We know1 = 1Is absolutely true , So the final presentation is all the database data . This is the timePreparedStatementIt becomes the key , stayPreparedStatementinSQLStatements are precompiled ,SQLThe structure of the statement is also designed at the beginning , Adopt settings?To fill in parameters , So it can't be realized by some strange charactersSQLInject .
Database tool class
We know that the database connection is written repeatedly 、 Closing this code is a very boring thing , We can't write this same piece of code many times in a project , This will greatly reduce the efficiency of writing code , So we came up with a way to package these operations into a Java class , And the basic information of database connection is stored by configuring the resource configuration file .
public class JDBCUtil {
private static final String driver;
private static final String url;
private static final String userName;
private static final String password;
static {
InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
try {
properties.load(is);
} catch (IOException e) {
e.printStackTrace();
}
driver = properties.getProperty("driver");
url = properties.getProperty("url");
userName = properties.getProperty("username");
password = properties.getProperty("password");
}
// Get database connection
public static Connection getConnection() {
Connection con = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(url, userName, password);
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return con;
}
// Database query , Return result set
public static ResultSet query(Connection con, PreparedStatement st, ResultSet rs, String sql
, Object[] params) throws SQLException {
st = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
if (params != null) {
for (int i = 0; i < params.length; i++) {
st.setObject(i + 1, params[i]);
}
}
rs = st.executeQuery();
return rs;
}
// Database addition, deletion and modification
public static int update(Connection con, String sql
, Object[] params, ResultSet rs, PreparedStatement st) throws SQLException {
st = con.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
st.setObject(i + 1, params[i]);
}
return st.executeUpdate();
}
// Close database connection
public static void release(Connection con, Statement st, ResultSet rs) {
boolean flag = true;
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
if (st != null) {
try {
st.close();
st = null;
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
if (con != null) {
try {
con.close();
con = null;
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
}
}
db.properties file
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/XXX?&useSSL=false&serverTimezone=UTC
username=root
password=123456
about db.properties We need to create this resource file in the project , First we need to create a folder resources

Create a resource file under this folder db

Then enter the basic information of the configuration database , Last but not least JDBCUtil Class to operate on the database .
} catch (SQLException e) {
e.printStackTrace();
flag = false;
}
}
}
}
`db.properties` file
```properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/XXX?&useSSL=false&serverTimezone=UTC
username=root
password=123456
about db.properties We need to create this resource file in the project , First we need to create a folder resources
Create a resource file under this folder db

Then enter the basic information of the configuration database , Last but not least JDBCUtil Class to operate on the database .
边栏推荐
- 根据给定字符数和字符,打印输出“沙漏”和剩余数
- Soft exam summary
- Leetcode question brushing - sorting
- [Yugong series] go teaching course 009 in July 2022 - floating point type of data type
- MySQL 8 of relational database -- deepening and comprehensive learning from the inside out
- 2018-UperNet ECCV
- Follow teacher Wu to learn advanced numbers - function, limit and continuity (continuous update)
- There is still a chance
- mosquitto_ Sub -f parameter use
- [paper reading] q-bert: Hessian based ultra low precision quantification of Bert
猜你喜欢

"Focus on machines": Zhu Songchun's team built a two-way value alignment system between people and robots to solve major challenges in the field of human-computer cooperation

Only simple function test? One article takes you to advanced interface automatic testing technology in 6 steps
![[FPGA tutorial case 18] develop low delay open root calculation through ROM](/img/c3/02ce62fafb662d6b13aedde79e21fb.png)
[FPGA tutorial case 18] develop low delay open root calculation through ROM

Consumer electronics, frozen to death in summer

ECCV 2022 | CMU proposes to recurse on the visual transformer without adding parameters, and the amount of calculation is still small

Is there any charge for PDF processing? impossible

Hanyuan high tech Gigabit 2-optical 6-conductor rail managed Industrial Ethernet switch supports X-ring redundant ring network one key ring network switch

12代酷睿处理器+2.8K OLED华硕好屏,灵耀14 2022影青釉商务轻薄本

Shell笔记(超级完整)
![[jetson][转载]jetson上安装pycharm](/img/65/ba7f1e7bd1b39cd67018e3f17d465b.png)
[jetson][转载]jetson上安装pycharm
随机推荐
On memory computing integrated chip technology
10 suggestions for 10x improvement of application performance
Science fiction style, standard 6 airbags, popular · yachts from 119900
[QNX hypervisor 2.2 user manual]7.2.1 hypervisor tracking events
“为机器立心”:朱松纯团队搭建人与机器人的价值双向对齐系统,解决人机协作领域的重大挑战
PDF处理还收费?不可能
Follow teacher Li to learn online generation - matrix (continuously updated)
Static resource mapping
DW: optimize the training process of target detection and more comprehensive calculation of positive and negative weights | CVPR 2022
跟着武老师学高数——函数、极限和连续(持续更新)
[jetson][转载]jetson上安装pycharm
Only simple function test? One article takes you to advanced interface automatic testing technology in 6 steps
二次握手??三次挥手??
Is there any charge for PDF processing? impossible
Network picture to local picture - default value or shortcut key
Hanyuan high tech Gigabit 2-optical 6-conductor rail managed Industrial Ethernet switch supports X-ring redundant ring network one key ring network switch
关系型数据库之MySQL8——由内而外的深化全面学习
静态资源映射
leetcode刷题——排序
ModuleNotFoundError: No module named ‘pywt‘解决方法