当前位置:网站首页>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) {
}
}
}
边栏推荐
- A treasure open source software, cross platform terminal artifact tabby
- 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
- Powerful blog summary
- Hcip day 16 notes
- Comparable interface and comparator interface
- 炒股開戶傭金優惠怎麼才能獲得,網上開戶安全嗎
- Take you to master the formatter of visual studio code
- 2022 chemical automation control instrument examination content and chemical automation control instrument simulation examination
- [Happy Valentine's day] "I still like you very much, like sin ² a+cos ² A consistent "(white code in the attached table)
- D28:maximum sum (maximum sum, translation)
猜你喜欢
Interesting 10 CMD commands
How to make icons easily
To rotate 90 degrees clockwise and modify the video format
Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
In 2022, 6G development has indeed warmed up
Qtoolbutton - menu and popup mode
Summary of fluent systemchrome
Analysis of refrigeration and air conditioning equipment operation in 2022 and examination question bank of refrigeration and air conditioning equipment operation
A treasure open source software, cross platform terminal artifact tabby
Schematic diagram of crystal oscillator clock and PCB Design Guide
随机推荐
Fluent learning (5) GridView
[automation operation and maintenance novice village] flask-2 certification
A treasure open source software, cross platform terminal artifact tabby
Opengauss database log management guide
D23:multiple of 3 or 5 (multiple of 3 or 5, translation + solution)
Recursive least square adjustment
Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
2.14 summary
X Opencv feature point detection and matching
Errors taken 1 Position1 argument but 2 were given in Mockingbird
How to quickly build high availability of service discovery
File copy method
Druids connect to mysql8.0.11
Ppt image processing
Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
C # basic knowledge (2)
Introduction to the gtid mode of MySQL master-slave replication
Format cluster and start cluster
webAssembly
Subset enumeration method