当前位置:网站首页>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) {
}
}
}边栏推荐
- C3p0 connection MySQL 8.0.11 configuration problem
- Simple solution of m3u8 file format
- Comment obtenir une commission préférentielle pour l'ouverture d'un compte en bourse? Est - ce que l'ouverture d'un compte en ligne est sécurisée?
- 2022.02.13
- How can enterprises and developers take advantage of the explosion of cloud native landing?
- The 2022 global software R & D technology conference was released, and world-class masters such as Turing prize winners attended
- 2022 examination of safety production management personnel of hazardous chemical production units and examination skills of safety production management personnel of hazardous chemical production unit
- Hcip day 14 notes
- The reason why the computer runs slowly and how to solve it
- IO flow review
猜你喜欢

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

Loop compensation - explanation and calculation of first-order, second-order and op amp compensation

How to solve the problem of requiring a password when accessing your network neighborhood on your computer

How to restore the factory settings of HP computer

Programming language (2)

Selenium check box

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

Apple released a supplementary update to MacOS Catalina 10.15.5, which mainly fixes security vulnerabilities

Recursive least square adjustment

The first game of the new year, many bug awards submitted
随机推荐
How can I get the Commission discount of stock trading account opening? Is it safe to open an account online
Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
2022 chemical automation control instrument examination content and chemical automation control instrument simulation examination
MLX90614 driver, function introduction and PEC verification
Unique in China! Alibaba cloud container service enters the Forrester leader quadrant
Errors taken 1 Position1 argument but 2 were given in Mockingbird
Enter MySQL in docker container by command under Linux
QT creator source code learning note 05, how does the menu bar realize plug-in?
Overview of Yunxi database executor
D23:multiple of 3 or 5 (multiple of 3 or 5, translation + solution)
Schematic diagram of crystal oscillator clock and PCB Design Guide
540. Single element in ordered array
The first game of the new year, many bug awards submitted
Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
"Learning notes" recursive & recursive
Minimum commission for stock account opening. Stock account opening is free. Is online account opening safe
Meta metauniverse female safety problems occur frequently, how to solve the relevant problems in the metauniverse?
Current detection circuit - including op amp current scheme
D25:sequence search (sequence search, translation + problem solving)
ADB command to get XML