当前位置:网站首页>JDBC Technology
JDBC Technology
2022-07-03 23:23:00 【Xi Wu Wen Lu】
One 、java Database programming foundation
Java Database programming in is through JDBC(Java Database Connectivity) Realized . Use JDBC Technology involves three different roles :Java official 、 Developers and database vendors . As shown in the figure below :

The three different roles involved in the above figure are responsible for different functions , As shown below :
- Java Official supply JDBC Interface , Such as Connection、Statement and ResultSet etc.
- In order to support Java Language uses its own database , They provide specific implementation classes based on these interfaces , These concrete implementation classes are called JDBC Driver(JDBC The driver ).
- For developers ,JDBC Provides a consistent API, Developers don't need to care about the details of implementing interfaces .
JDBC API by Java Developers use the database to provide a unified programming interface , It consists of a group of Java Class and interface . Such classes and interfaces come from java.sql and javax.sql Two bags .
Two 、 Database programming process
The general process of database programming is shown in the figure below , Among them, query (Read) The process requires at most 7 A step , modify (C Insert 、U to update 、D Delete ) The process requires at most 6 A step . This process uses precompiled statement objects for data operations , Therefore, it is possible to bind parameters , See the first 4 step .

The above steps are basic general steps , The actual situation will change , For example, no parameters need to be bound , Is the first 4 The steps are omitted . also , If Connection object 、Statement Objects and ResultSet Objects use automatic resource management technology to release resources , So the first 7 Steps can also be omitted .
1) When programming database connection ,JVM You must first load the database driver provided by a specific manufacturer . Use Class.forName() Method realization Driver loading The process , as follows :
Class.forName("com.mysql.jdbc.Driver");
2) Establish a database connection
After the driver is loaded successfully, you can connect to the database . The database connection can be established by calling DriverManager Class getConnection() Method realization
3) establish SQL Statement object (Statement)( Transmitter object )
conn.createStatement(); conn.prepareStatement(sql);
4) Set parameters ( if necessary )
5) Perform the operation , function SQL sentence
6)Resultset Object to get the result
ResultSet Objects are used to encapsulate sql Statement query results , It's also a very important object . This object provides the method of traversing data and getting data .
7) Release resources
3、 ... and 、 The interface is introduced
JDBC API There are three important interfaces in , Respectively Connection、Statement as well as ResultSet.
3.1 Connection Interface
Connection The implementation object of the interface represents the connection with the database , That is to say Java Establish a connection between the program and the database .Connection Methods commonly used in interfaces :
- Statement createStatement(): Create a statement object , The statement object is used to put SQL Statements are sent to the database .
- PreparedStatement prepareStatement(String sql): Create a precompiled statement object , Used to parameterize SQL Statements are sent to the database , The parameter contains one or more question marks “?” Place holder .
- CallableStatement prepareCall(String sql): Create a statement object that calls the stored procedure , Parameters are called stored procedures , The parameter contains one or more question marks “?” As a placeholder .
- close(): Close the connection to the database , You must close the connection after using , Otherwise, the connection will remain for a long time , Until timeout .
- isClosed(): Determine whether the connection has been closed .
3.2 Statement Interface
Statement It is called a statement object , It provides for sending SQL sentence , And visit the results .Connection Interface provides generation Statement Methods , Generally speaking, it can be through connection.createStatement() You can get Statement object .
There are three kinds of Statement Interface :Statement、PreparedStatement and CallableStatement, among PreparedStatement Inherit Statement Interface ,CallableStatement Inherit PreparedStatement Interface .Statement Implementation objects are used to perform basic SQL sentence ,PreparedStatement Implementation objects are used to perform precompiled SQL sentence ,CallableStatement Implementation objects are used to call stored procedures in the database .
Statement There are many ways , The most common methods are as follows :
- executeQuery(): Run the query statement , return ResultSet object .
- executeUpdate(): Run update operation , Returns the number of updated rows .
- close(): Close the statement object .
- isClosed(): Judge whether the statement object has been closed .
3.3 ResultSet Interface
stay Statement perform SQL When the sentence is , If it is SELET Statement will return the result set , The result set passes through the interface ResultSet Description of the , It provides a way to access the result set row by row , Through this method, you can access the contents of different fields in the result set .
ResultSet Provides methods to retrieve different types of fields , The most commonly used methods are introduced as follows :
- close(): Close result set object .
- isClosed(): Judge whether the result set object has been closed .
- next(): Move the cursor of the result set back one line from its current position .
- getString(): Get in the database yes CHAR or VARCHAR Data of string type , The return value type is String.
- getFloat(): Get data of floating-point type in the database , The return value type is float.
- getDouble(): Get data of floating-point type in the database , The return value type is double.
- getDate(): Get data of date type in the database , The return value type is java.sql.Date.
- getBoolean(): Get the type of Boolean data in the database , The return value type is boolean.
- getBlob(): Get in the database yes Blob( Binary large objects ) Data of type , The return value type is Blob type .
Four 、 Example :
public static void main( String[] args )
{
Connection con = null; // Define a MYSQL Link to
PreparedStatement ps = null; // Statement object
ResultSet rs = null;
String sql = "SELECT * FROM country where id = ?;"; //sql sentence ,? Is the parameter
try{
// load Mysql drive
Class.forName("com.mysql.cj.jdbc.Driver");
// Get database connection object
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis?useSSL=false", "root", ""); // Link to local MYSQL
// Instantiation PreparedStatement
ps = con.prepareCall(sql);
// Set parameters
ps.setInt(1,1);
// perform sql
rs = ps.executeQuery();
// To get the results
if(rs.next()){
System.out.println(rs.getString(2));
}
}catch (ClassNotFoundException | SQLException e){
e.printStackTrace();
}finally {
// Release resources
try {
if (ps != null) ps.close();
if (con != null) con.close();
if (rs != null) rs.close();
} catch (SQLException ignored) {
}
}
}边栏推荐
- Pyqt5 sensitive word detection tool production, operator's Gospel
- Classification and extension of OC
- How to restore the factory settings of HP computer
- D26: the nearest number (translation + solution)
- Comparable interface and comparator interface
- "Learning notes" recursive & recursive
- URLEncoder. Encode and urldecoder Decode processing URL
- [automation operation and maintenance novice village] flask-2 certification
- How can enterprises and developers take advantage of the explosion of cloud native landing?
- Amway by head has this project management tool to improve productivity in a straight line
猜你喜欢

Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?

Unique in China! Alibaba cloud container service enters the Forrester leader quadrant

The 2022 global software R & D technology conference was released, and world-class masters such as Turing prize winners attended
![[Happy Valentine's day]](/img/d9/9280398eb64907a567df6eea772adb.jpg)
[Happy Valentine's day] "I still like you very much, like sin ² a+cos ² A consistent "(white code in the attached table)

How to prevent malicious crawling of information by one-to-one live broadcast source server

2022 chemical automation control instrument examination content and chemical automation control instrument simulation examination

Blue Bridge Cup -- guess age

MLX90614 driver, function introduction and PEC verification

"Learning notes" recursive & recursive

How to connect a laptop to a projector
随机推荐
ThreadLocal function, scene and principle
股票开户佣金最低的券商有哪些大家推荐一下,手机上开户安全吗
Arc135 partial solution
Meta metauniverse female safety problems occur frequently, how to solve the relevant problems in the metauniverse?
Open 2022 efficient office, starting from project management
2022.02.14
Blue Bridge Cup -- Mason prime
Firefox set up proxy server
Flutter internationalized Intl
JarPath
Shiftvit uses the precision of swing transformer to outperform the speed of RESNET, and discusses that the success of Vit does not lie in attention!
Fluent learning (4) listview
Sword finger offer day 4 (Sword finger offer 03. duplicate numbers in the array, sword finger offer 53 - I. find the number I in the sorted array, and the missing numbers in sword finger offer 53 - ii
C # basic knowledge (2)
Loop compensation - explanation and calculation of first-order, second-order and op amp compensation
The interviewer's biggest lie to deceive you, bypassing three years of less struggle
Pan Yueming helps Germany's Rochester Zodiac custom wristwatch
2022 chemical automation control instrument examination content and chemical automation control instrument simulation examination
Pandaoxi's video
股票開戶傭金最低的券商有哪些大家推薦一下,手機上開戶安全嗎