当前位置:网站首页>JDBC programming of MySQL database
JDBC programming of MySQL database
2022-07-06 23:16:00 【No smell of flowers】
️ In front of the word ️
This article will introduce JDBC Programming ,JDBC(Java DataBase Connectivity,java Database connection ) It's one for execution SQL Of the statement Java API, It can provide unified access for a variety of relational databases , It's used by a group Java Language written classes and interfaces .
Blog home page : The blog home page without flowers
Welcome to focus on the likes collection ️ Leaving a message.
This paper is written by No smell of flowers original ,CSDN First episode !
Starting time :2022 year 7 month 4 Japan
️ Persistence and hard work will surely bring poetry and distance !
Recommended books :《 High performance MySQL》
Refer to the online programming website : Cattle from Power button
Blogger's code cloud gitee, Usually the program code written by bloggers is inside .
Blogger's github, Usually the program code written by bloggers is inside .
The author's level is very limited , If an error is found , Be sure to inform the author in time ! Thank you thank you !
Navigation assistant

1.JDBC Front work
1.1 Get ready MySQL Drive pack
MySQL Of jdbc We can download the driver package on the official website , We can maven Central warehouse download , This maven What is the central warehouse ? You can understand it as “ The app store ” Software , Its function is similar to that of the app store , It's just that there are mobile apps in the mobile app store , and maven There are many in the central warehouse API And dependency packages .
Now? MySQL Has been Oracle Acquired ,Oracle Of “ table manners ” It's a little ugly , You can find it on the official website , But I feel maven The central warehouse is better , So we arrived maven Central warehouse download jdbc Drive pack .
website :maven The central warehouse
First step , Click the website to enter maven The central warehouse .
The second step , Search for MySQL, Choose the one shown below .
The third step , Click to enter , Find the corresponding large version jdbc Drive pack , If your MySQL yes 5 Version of the driver package also choose 5 Version of , Of course if your MySQL yes 8 edition , Then choose your driver package 8 edition .
my MySQL yes 5 So I choose the larger version as 5 Driver package .
Step four , Click in , Follow the diagram below , Download the driver package .
After downloading, our driver package is ready .
1.2 Create project
Use the compiler to create a project , After the project is created , Follow the steps below :
First step , Create a directory , Name at will , It might as well be called lib Catalog .
The second step , Copy the downloaded driver package to this directory .
The third step , set an option , Right click the directory that you just created and copied the driver package , find As a Lib…

In this way, our driver package will be imported into our project , Then we can write jdbc Code. .
2.JDBC Programming steps
2.1 create data source DataSource
First step , establish DataSource object , To describe where the database is .
DataSource dataSource = new MysqlDataSource();
among DataSource by java.sql One of the inside jdbc Interface ,MysqlDataSource It comes from an implementation in the driver package we downloaded DataSource The class of the interface .
The second step , Set the “ Location ”(URL), Login database account name and password .
// Set the address of the database
((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/jdbctest/characterEncoding=utf8&useSSL=false");
// Set the account name for logging into the database
((MysqlDataSource)dataSource).setUser("root");
// Set the password to log in to the database
((MysqlDataSource)dataSource).setPassword("123456");
jdbc:mysql://127.0.0.1:3306/jdbctest?characterEncoding=utf8&useSSL=false It's just one. URL, Also called unique resource locator .jdbc:mysql It means that we should url Is used for jdbc mysql Of URL, Because there are many databases , More than jdbc A kind of , So it needs to be subdivided .
Specific meaning independent comparison :URL Type declaration :// The address of the database / Database name ? Character set encoding & Is it encrypted .
2.2 Connect to database
The third step , Establish a connection with the server , Create a data source DataSource After the object , Calling the getConnection() Method , obtain java.sql.Connection object , This will establish a connection with the database .
Connection connection = dataSource.getConnection();
2.3 Construct and execute sql sentence ( Insert operation as an example )
Step four , structure sql Statement string , And wrap the statement as PreparedStatement object , That is to call Connection Object's prepareStatement Method , Parameter is sql character string , Will return a PreparedStatement object , Then we call PreparedStatement Object executeUpdate Method or executeQuery Method execution sql sentence .
Let's take the insertion operation as an example .
// Operating the database The key is to construct sql sentence
//jdbc Tectonic sql Statements do not need to be accompanied by ;
String sql = "insert into student values(1, ' Zhang San ')";
// take sql String wrapped into a statement object , Indicates to be executed sql The object of
PreparedStatement statement = connection.prepareStatement(sql);
// perform sql
// If it is to be implemented sql Statement operation is insert, update, delete, Then use executeUpdate Method execution , The return value is the number of rows that affect the data
// If it is to be implemented sql Statement operation is select, Then use executeQuery Method execution
int ret = statement.executeUpdate();
among , If it is to be implemented sql Statement operation is insert, update, delete, Then use executeUpdate Method execution , The return value is the number of rows that affect the data , If it is to be implemented sql Statement operation is select, Then use executeQuery Method execution , The return value is one ResultSet Result table object .
2.4 Release resources in time
Step five , Release resources , We are finished sql You need to release resources in time after the statement , stay JDBC Programming , The most common classes or interfaces that need to be released are three , Namely Connection,PreparedStatement,ResultSet, The first two of them are jdbc It has been used in the insert operation , And the last one , namely ResultSet, It is used when executing query statements , call executeQuery Method after executing the query statement , Will return a “ A temporary table ”, The “ A temporary table ” The results of the query are stored on , We can get the result of querying the database by traversing the result table .
// here sql The statement has been executed , Need to release resources
statement.close();
connection.close();
Use jdbc Program to insert all the code :
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class TestJdbc {
public static void main(String[] args) throws SQLException {
DataSource dataSource = new MysqlDataSource();
// Set the address of the database
((MysqlDataSource)dataSource).setURL("jdbc:mysql://127.0.0.1:3306/jdbctest?characterEncoding=utf8&useSSL=false");
// Set the account name for logging into the database
((MysqlDataSource)dataSource).setUser("root");
// Set the password to log in to the database
((MysqlDataSource)dataSource).setPassword("123456");
// Establishing a connection
Connection connection = dataSource.getConnection();
// Operating the database The key is to construct sql sentence
//jdbc Tectonic sql Statements do not need to be accompanied by ;
String sql = "insert into student values(1, ' Zhang San ')";
// take sql String wrapped into a statement object , Indicates to be executed sql The object of
PreparedStatement statement = connection.prepareStatement(sql);
// perform sql
// If it is to be implemented sql Statement operation is insert, update, delete, Then use executeUpdate Method execution , The return value is the number of rows that affect the data
// If it is to be implemented sql Statement operation is select, Then use executeQuery Method execution
int ret = statement.executeUpdate();
// here sql The statement has been executed , Need to release resources
statement.close();
connection.close();
}
}
Running results , We observe by querying the results of the tables in the database :
mysql> create database jdbctest;
Query OK, 1 row affected (0.01 sec)
mysql> use jdbctest;
Database changed
mysql> create table student(id int, name varchar(20));
Query OK, 0 rows affected (0.02 sec)
mysql> show tables;
+--------------------+
| Tables_in_jdbctest |
+--------------------+
| student |
+--------------------+
1 row in set (0.00 sec)
-- perform jdbc Query after code
mysql> select * from student;
+------+--------+
| id | name |
+------+--------+
| 1 | Zhang San |
+------+--------+
1 row in set (0.00 sec)
Program run results , Express 1 The line has been affected .
2.5 Don't write dead code ( Take insertion, for example )
We found our sql The sentence is completely written , This is not good , We can use the input operation to let users input information for insertion , Then we need to use Scanner The class .
After we get the information entered by the user , We need to integrate information , The easiest way to think of is string splicing , But it has the following disadvantages , First, it is easy to make mistakes , Especially when there are many single and double quotation marks , Second, it's not safe , Hackers can use sql Injection to modify the database .
So a better way is to sql The information to be input in the string uses ? Instead of or called space occupying , And then through PreparedStatement Medium setXXX A series of methods to set each ? What is the content of .
This series of methods , First parameter representation sql How many objects to be executed ?, The second parameter indicates that this ? What to set up . such as :
// Operating the database The key is to construct sql sentence
//jdbc Tectonic sql Statements do not need to be accompanied by ;
String sql = "insert into student values(?, ?)";
// take sql String wrapped into a statement object , Indicates to be executed sql The object of
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, id);
statement.setString(2, name);
Complete code :jdbc Insert operation source code
Running results :
Database query results :
mysql> select * from student;
+------+--------+
| id | name |
+------+--------+
| 1 | Zhang San |
| 2 | Li Si |
+------+--------+
2 rows in set (0.00 sec)
2.6JDBC Delete , update operation
stay jdbc Programming , Delete operation and update operation , Its steps are exactly the same as the insertion operation , It's just constructed sql Statements are different , Everything else is the same .
Delete operation key code :
// User input
System.out.println(" Please enter the student number to be deleted :");
int id = sc.nextInt();
// Operating the database The key is to construct sql sentence
//jdbc Tectonic sql Statements do not need to be accompanied by ;
String sql = "delete from student where id = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, id);
System.out.println("statement" + statement);
jdbc Delete operation complete code : Source code address
Program run results :
Database query results :
mysql> select * from student;
+------+--------+
| id | name |
+------+--------+
| 1 | Zhang San |
+------+--------+
1 row in set (0.00 sec)
Update operation key code :
// User input What needs to be revised id And the modified name
System.out.println(" Please enter the student number to be modified :");
int id = sc.nextInt();
sc.nextLine();
System.out.println(" Please enter the modified name :");
String afterName = sc.nextLine();
// Operating the database The key is to construct sql sentence
//jdbc Tectonic sql Statements do not need to be accompanied by ;
String sql = "update student set name = ? where id = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, afterName);
statement.setInt(2, id);
System.out.println("statement" + statement);
jdbc Update operation complete code : Source code address
Program run results :

Database query results :
mysql> select * from student;
+------+--------+
| id | name |
+------+--------+
| 1 | Wang Wu |
+------+--------+
1 row in set (0.00 sec)
2.7JDBC Query operation
jdbc The query operation of is a little different from the insert, delete and update operation , Execute the query sql Statement is called executeQuery Method to execute the statement , And it will bring back the query results , We can obtain the results of the query through operations similar to iterators , After using this result set, you need to release it .
Key code :
// Operating the database The key is to construct sql sentence
//jdbc Tectonic sql Statements do not need to be accompanied by ;
String sql = "select * from student";
PreparedStatement statement = connection.prepareStatement(sql);
// perform sql The query operation does not return int It's a temporary table Use ResultSet Object represents this temporary table
ResultSet ret = statement.executeQuery();
// Convenient result set
// Expected result format
// +------+--------+
// | id | name |
// +------+--------+
// | 1 | Wang Wu |
// +------+--------+
while (ret.next()) {
int id = ret.getInt("id");
String name = ret.getString("name");
System.out.println("id:" + id + ", name:" + name);
}
// close resource
ret.close();
statement.close();
connection.close();
jdbc Query operation complete code : Source code address
Program run results :
Okay ,JDBC The whole content of is almost these , All complete code links : Address .
Next up : Database transactions

边栏推荐
- dockermysql修改root账号密码并赋予权限
- COSCon'22 社区召集令来啦!Open the World,邀请所有社区一起拥抱开源,打开新世界~
- 新手问个问题,我现在是单机部署的,提交了一个sql job运行正常,如果我重启了服务job就没了又得
- mysql连接vscode成功了,但是报这个错
- mysql-cdc 的jar包 ,在flink运行模式下,是不是要放在不同的地方呢?
- [untitled]
- Is "applet container technology" a gimmick or a new outlet?
- 每人每年最高500万经费!选人不选项目,专注基础科研,科学家主导腾讯出资的「新基石」启动申报...
- Dayu200 experience officer runs the intelligent drying system page based on arkui ETS on dayu200
- AI表现越差,获得奖金越高?纽约大学博士拿出百万重金,悬赏让大模型表现差劲的任务...
猜你喜欢

云原生(三十二) | Kubernetes篇之平台存储系统介绍

PDF批量拆分、合并、书签提取、书签写入小工具

Dayu200 experience officer homepage AITO video & Canvas drawing dashboard (ETS)

GPT-3当一作自己研究自己,已投稿,在线蹲一个同行评议

Cloud native (32) | kubernetes introduction to platform storage system

欧洲生物信息研究所2021亮点报告发布:采用AlphaFold已预测出近1百万个蛋白质

Efficient ETL Testing

#DAYU200体验官# 首页aito视频&Canvas绘制仪表盘(ets)
mysql拆分字符串作为查询条件的示例代码

cuda 探索
随机推荐
(DART) usage supplement
mysql-cdc 的jar包 ,在flink运行模式下,是不是要放在不同的地方呢?
How does crmeb mall system help marketing?
Dockermysql modifies the root account password and grants permissions
docker中mysql开启日志的实现步骤
问下各位,有没有flink sql生成作业的文档啊或是案列啊知道flink cli可以建表和指定目
AcWing 4299. Delete point
The problem of ASP reading Oracle Database
COSCon'22 社区召集令来啦!Open the World,邀请所有社区一起拥抱开源,打开新世界~
使用MitmProxy离线缓存360度全景网页
DR-Net: dual-rotation network with feature map enhancement for medical image segmentation
B站大佬用我的世界搞出卷積神經網絡,LeCun轉發!爆肝6個月,播放破百萬
Thinkphp5 multi table associative query method join queries two database tables, and the query results are spliced and returned
MySQL中正则表达式(REGEXP)使用详解
Ajout, suppression et modification d'un tableau json par JS
Introduction to network basics
Balanced Multimodal Learning via On-the-fly Gradient Modulation(CVPR2022 oral)
Is "applet container technology" a gimmick or a new outlet?
#DAYU200体验官# 首页aito视频&Canvas绘制仪表盘(ets)
Cocoscreator+typescripts write an object pool by themselves