当前位置:网站首页>JDBC programming of MySQL
JDBC programming of MySQL
2022-07-23 21:59:00 【Zzt.opkk】
MySQL Of JDBC Programming
1. Conditions for database programming
- programing language : Java,C,C++,Python…
- database : Oracle,MySQL,SQLServer…
- Database driver package : Different databases , Different database driver packages are provided for different programming languages ,
- Such as :MySQL Provides Java Driver package mysql-connector-java, Need to be based on Java operation MySQL That is, you need the driver package . alike ,
Based on Java operation Oracle Database is required Oracle Database driver package ojdbc .
- Such as :MySQL Provides Java Driver package mysql-connector-java, Need to be based on Java operation MySQL That is, you need the driver package . alike ,
2. JDBC Programming
JDBC, namely Java Database Connectivity,java Database connection , It's one for execution SQL Of the statement Java API( A fairly widely used term in computers Application Programming Interface Some functions are provided / Method / class , Programmers can call directly to complete some functions ), be called " database SDK"(software development kit, SDK Broader concept , In addition to providing API outside , There are also some executable programs ( Tools ) Auxiliary development / debugging …), You can use these API Convenient access to database server .
about MySQL/Oracle/SQLServer The client side. / Server structured program , Then the operation database is Through the official command line client / Graphical interface / Code Which one of them ? Now the mainstream way to operate the database is through code manipulation .
In the early days, different databases provided API It's not the same , Very unfriendly to programmers , therefore Java Provide a set of " standard " Interface system of , Let these database manufacturers . Provided API All go to Java In this interface system , So programmers only need to master Java This article API You can adapt to all common mainstream databases .Java This set of operation database API, It's called JDBC.
3. JDBC working principle
JDBC It provides a unified access method for a variety of relational databases , Access as a vendor specific database API A high-level abstraction of , It mainly contains some general interface classes
JDBC Access the database hierarchy :
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-M7jd2PDR-1658300956096)(C:\Users\a\AppData\Roaming\Typora\typora-user-images\image-20220717150318903.png)]](/img/12/b8cc8ad7c22e105573805b0ef76811.png)
JDBC advantage :
- Java Language access database operation is completely oriented to abstract interface programming
- The development of database applications is not limited to the specific database manufacturers API
- The portability of the program is greatly enhanced
4. JDBC Use
4.1 Operating the database - Insert
To operate the database , First, connect to the database , To connect to the database , You have to describe the location of the database . stay JDBC in , Use DataSource This class describes MySQL Server location ,
//DataSource It's a interface, Cannot instantiate directly . and MysqlDataSource Is to achieve DataSource, This class is from the driver package . // This operation is - Upward transformation DataSource dataSource = new MysqlDataSource(); // Connect to server - Move down ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java104?characterEncoding=utf8&useSSL=false");Someone here will have questions , Why not use it directly MysqlDataSource To instantiate objects ? Isn't this very convenient ?
MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setUrl();Although there is no difference between the two ways of writing . But in the actual development, we may see the first way more .
- In the first way , Got The data source is DataSource type . Write other code later , Method / class , If you use a data source , The type of holding is also DataSource type ,DataSource yes General type , It can refer to any database . Once needed in the future Change database , Code changes are very small , Just change the instantiation code , No other code changes .
- The second way , The data source obtained is MysqlDataSource type . Other subsequent codes , Method / class , If you use a data source , The type of holding is MysqlDataSource, and MysqlDataSource Just for MySQL The type of . Once the database is replaced in the future , You may need to put the scattered in all parts of the code MysqIDataSource Change the type .
The first method greatly improves the maintainability of the code , Expansibility .
//MySQL Data connection URL The parameter format is as follows : jdbc:mysql:// Server address : port / Database name ? Parameter name = Parameter values![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-KDaYDy3a-1658300956098)(C:\Users\a\AppData\Roaming\Typora\typora-user-images\image-20220717155040996.png)]](/img/a8/0dc90f1b81460f2367c587db304c48.png)
Enter your username and password :
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("123456");
So pass IP Address , Port number , Database name , The user name and password describe the location of the database .
- Create a connection with the database server
In network communication , There are two styles , One is ’ There is a connection ’, amount to " Make a phone call "; The other is ’ There is no connection ’, amount to " Send wechat ".
The data is based on " There is a connection " The way , Mainly before communication , First, check whether the communication link is smooth , There's a downside , Connections need to be managed , The unused connections need to be released in time ( Like on the phone , Forget to hang up , As a result, the connection cannot be disconnected , The phone bill is kept slowly ~~).
// Import import java.sql.Connection Under bag Connection class
Connection connection = dataSource.getConnection();
System.out.println(connection);
// If the output object is [email protected] Description of the connection is successful
// Also pay attention to throwing exceptions Import import java.sql.SQLException;
- Operating the database
Use SQL sentence , utilize JDBC To manipulate the database , The essence is still to use SQL To manipulate the database
// Create database
create table student(id int primary key, name varchar(20));
String sql = "insert into student values(1, ' Zhang San ');";
adopt PreparedStatement Object to tell SQL The statement executed , Of this object SQL Is from this string .
PreparedStatement statement = connection.prepareStatement(sql);
You can also fill in the following way :
Scanner in = new Scanner(System.in);
System.out.println(" Please enter the student number :");
int id = in.nextInt();
System.out.println(" Please enter a name :");
String name = in.next();
String sql = "insert into student values(?, ?);";//? As a placeholder
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, id); // The default from the 1 Start
statement.setString(2, name);
- perform SQL sentence
int n = statement.executeUpdate();
System.out.println(n);
here insert,update,delete It's through executeUpdate To execute , The return value is an integer , This operation affects several lines ,select It's through executeQuery To execute .
- disconnect
statement.close();
connection.close();
notes : After the creation of the first release
4.2 operation
4.2.1 Modify the record
public static void main(String[] args) throws SQLException {
//1. Find the data source
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java_learn?characterEncoding=utf8&useSSL=false");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("123456");
//2. Establishing a connection
Connection connection = dataSource.getConnection();
//3. Enter modification information
Scanner in = new Scanner(System.in);
System.out.println(" Please enter the student ID of the student you want to modify :");
int id = in.nextInt();
System.out.println(" The student's revised name :");
String name = in.next();
//3. structure SQL sentence
String sql = "update student set name = ? where id = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1,id);
statement.setString(2, name);
//4. perform SQL
int n = statement.executeUpdate();
System.out.println(n);
//5. close resource
statement.close();
connection.close();
}
4.2.2 Delete record
public static void main(String[] args) throws SQLException {
//1. Find the data source
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java_learn?characterEncoding=utf8&useSSL=false");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("123456");
//2. Create connection
Connection connection = dataSource.getConnection();
//3. Enter information about deleting records
Scanner in = new Scanner(System.in);
System.out.println(" Please enter and delete student ID :");
int id = in.nextInt();
//4. structure SQL
String sql = "delete from student where id = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, id);
//5. perform SQL
int n = statement.executeUpdate();
System.out.println(n);
//6. close resource
statement.close();
connection.close();
}
4.2.3 find record
public static void main(String[] args) throws SQLException {
//1. create data source
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java_learn?characterEncoding=utf8&useSSL=false");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("123456");
//2. Establish connection with database
Connection connection = dataSource.getConnection();
//3. No need to input
//4. structure SQL
String sql = "select * from student";
PreparedStatement statement = connection.prepareStatement(sql);
//5. perform SQL
//executeQuery The return value of ResultSet object , Think of it as a A temporary table
ResultSet resultSet = statement.executeQuery();
//6. Traversal result set
// hold resultSet As an iterator
while (resultSet.next()) {
// adopt getXXX Method , To get
// take id, id The type is int, Use getInt
int id = resultSet.getInt("id");
// take name, The type is String Use getString
String name = resultSet.getString("name");
System.out.println(id + ":" + name);
}
//7. close resource
statement.close();
connection.close();
}
4.2.4 insert record
public static void main(String[] args) throws SQLException {
//1. Get the database location
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java_learn?characterEncoding=utf8&useSSL=false");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("123456");
//2. Connect to database
Connection connection = dataSource.getConnection();
System.out.println(connection);
//3. Use SQL sentence , utilize JDBC To manipulate the database , The essence is still through SQL To operate
/*String sql = "insert into student values(3, ' Zhang San ');";*/
Scanner in = new Scanner(System.in);
System.out.println(" Please enter the student number :");
int id = in.nextInt();
System.out.println(" Please enter a name :");
String name = in.next();
String sql = "insert into student values(?, ?);";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, id);
statement.setString(2, name);
//4. perform SQL sentence
// insert,update,delete It's through executeUpdate To execute
// select It's through executeQuery To execute
// The return value is an integer , This operation affects several lines
int n = statement.executeUpdate();
System.out.println(n);
//5. disconnect
statement.close();
connection.close();
}
4.3 Database connection
Connection The interface implementation class is provided by the database , obtain Connection Objects usually have two ways :
- adopt DriverManager( Driver management ) Static method to get
// load JDBC The driver
Class.forName("com.mysql.jdbc.Driver");
// Create database connection
Connection connection = DriverManager.getConnection(url);
- adopt DataSource( data source ) Object acquisition . It will be used in practical application DataSource object
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setUrl("url");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("123456");
Connection connection = dataSource.getConnection();
The difference :
- DriverManager Class to get Connection Connect , yes Can't reuse Of , Every time you release resources after use , adopt connection.close() Is to close the physical connection .
- DataSource Provide connection pool support . When the connection pool is initialized, a certain number of database connections will be created , These connections are Reusable , Every time you use the database connection , Release resource call connection.close() All are take Conncetion Connection object recycling .
4.4 Statement object
Statement The object is mainly to SQL Statements are sent to the database .JDBC API There are mainly three kinds of Statement object

The most commonly used in actual development is PreparedStatement object , The following is a summary :

Return value :
- executeQuery() Method returns a single The result set , Usually used for select sentence
- executeUpdate() Method return value is An integer , Indicates the number of lines affected , Usually used for update、insert、delete sentence
4.5 ResultSet object
ResultSet Object, which is called the result set , It represents compliance with SQL All lines of the statement condition , And it passes through a set of getXXX Method provides
Access to the data in these rows .
=“C:\Users\a\AppData\Roaming\Typora\typora-user-images\image-20220717203426690.png” alt=“image-20220717203426690” style=“zoom:50%;” />
Return value :
- executeQuery() Method returns a single The result set , Usually used for select sentence
- executeUpdate() Method return value is An integer , Indicates the number of lines affected , Usually used for update、insert、delete sentence
4.5 ResultSet object
ResultSet Object, which is called the result set , It represents compliance with SQL All lines of the statement condition , And it passes through a set of getXXX Method provides
Access to the data in these rows .
ResultSet The data in the are arranged row by row , Each row has multiple fields , And there are A record pointer , The data row indicated by the pointer is called the current data row , We Only the current data row can be operated . If we want to get a record , Then use ResultSet Of next() Method , If we want to get ResultSet Inside All records , It should be Use while loop
边栏推荐
- 给定一个以数字组成的数组,实现输出id为数字,并且从小到大排序的name
- 数据库系统概论第五版课后习题——第一章 绪论
- 机器学习习题——对率回归
- Several methods of obtaining longitude and latitude by cesium
- 软件体系结构期末复习六十题
- 存储结构和管理盘。有点像装win98要先分区格式化硬盘
- MySQL如何对SQL做prepare预处理(解决IN查询SQL预处理仅能查询出一条记录的问题)
- Postgraduate entrance examination | advanced mathematics Chapter4 indefinite integral
- U++ learning notes control object scale
- [complex overloaded operator]
猜你喜欢

Neo4j应用

Golang invalid argument to intn报错的解决

U++ learning notes control object scale

机器学习习题——对率回归

Apprentissage Lambda (utilisation du comparateur après tri, regroupement après collecte avec collectors.groupingby)

10 basic written interview questions, how many questions can you answer?

lambda学习(sort后面的Comparator的使用,collection后使用Collectors.groupingBy分组)
![[mathematical modeling summer training] location of distribution center](/img/d5/c9b4de6750a7ed080c194250629467.png)
[mathematical modeling summer training] location of distribution center

& 9 nodemon automatic restart tool

Neo4j application
随机推荐
How about opening an account for Haitong Securities? Is it safe
ADB 命令结合 monkey 的简单使用,超详细
【HiFlow】腾讯云新一代自动化助手,我用它完成了企业疫情提示(无代码)
U++ learning notes control object scale
A stack of digital robots were selected in Gartner's China AI market guide
Sixty final review questions of software architecture
Golang invalid argument to INTN
大淘营批量采集商品,如何将未上传的宝贝保存下来等后面再导入采集上传
Given an array composed of numbers, realize the name whose output ID is a number and sorted from small to large
Cesium core class viewer viewer details
[isprint function determines whether characters can be output]
Preliminary discussion on POC compilation
User manual of boost filesystem
Neo4j application
Golang invalid argument to intn报错的解决
How does MySQL prepare SQL (solve the problem that in query SQL preprocessing can only query one record)
Mqtt connection, subscription and publishing can be realized without mqtt C library
lambda学习(sort后面的Comparator的使用,collection后使用Collectors.groupingBy分组)
Bisection function details
Interval DP chain stone merging