当前位置:网站首页>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) {
}
}
}
边栏推荐
- C summary of knowledge point definitions, summary notes
- Comparable interface and comparator interface
- 2022 chemical automation control instrument examination content and chemical automation control instrument simulation examination
- Pyqt5 sensitive word detection tool production, operator's Gospel
- Opengauss database log management guide
- Apple released a supplementary update to MacOS Catalina 10.15.5, which mainly fixes security vulnerabilities
- Maxwell equation and Euler formula - link
- URLEncoder. Encode and urldecoder Decode processing URL
- Schematic diagram of crystal oscillator clock and PCB Design Guide
- The 2022 global software R & D technology conference was released, and world-class masters such as Turing prize winners attended
猜你喜欢
The difference between single power amplifier and dual power amplifier
"Learning notes" recursive & recursive
Hcip 13th day notes
Ppt image processing
Summary of fluent systemchrome
Scratch uses runner Py run or debug crawler
Blue Bridge Cup -- guess age
How can enterprises and developers take advantage of the explosion of cloud native landing?
Schematic diagram of crystal oscillator clock and PCB Design Guide
In VS_ In 2019, scanf and other functions are used to prompt the error of unsafe functions
随机推荐
FPGA tutorial and Allegro tutorial - link
In 2022, 6G development has indeed warmed up
Yyds dry goods inventory [practical] simply encapsulate JS cycle with FP idea~
[Android reverse] use the DB browser to view and modify the SQLite database (copy the database file from the Android application data directory | use the DB browser tool to view the data block file)
How to write a good title of 10w+?
The difference between single power amplifier and dual power amplifier
Unity shader visualizer shader graph
ADB command to get XML
2.14 summary
Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
Simple solution of m3u8 file format
How to solve the problem of computer networking but showing no Internet connection
Les sociétés de valeurs mobilières dont la Commission d'ouverture d'un compte d'actions est la plus faible ont ce que tout le monde recommande.
在恒泰证券开户怎么样?安全吗?
D24:divisor and multiple (divisor and multiple, translation + solution)
How to restore the factory settings of HP computer
Weekly leetcode - nc9/nc56/nc89/nc126/nc69/nc120
How to solve the problem of requiring a password when accessing your network neighborhood on your computer
How about opening an account at Hengtai securities? Is it safe?
Qtoolbutton available signal