当前位置:网站首页>Getting started with JDBC
Getting started with JDBC
2022-07-03 18:35:00 【Bieyunchao】
One 、 What is? JDBC?
Concept :Java DataBase Connectivity Java Database connection , Java Language operation database
Two 、JDBC The essence
JDBC The essence : Actually, it's official (sun company ) A set of rules defined to operate all relational databases , Interface . Each database manufacturer to implement this set of interface , Provide database driver jar package . We can use this interface (JDBC) Programming , The code that actually executes is the driver jar The implementation class in the package .
3、 ... and 、JDBC Quick start
1.JDBC Six steps to programming
First step : Registration drive ( effect : tell Java Program , Which brand database will be connected soon )
The second step : Get database connection ( Express JVM The channel between the database process and the database process is opened , This belongs to communication between processes , A heavyweight , Be sure to close the channel after use .)
The third step : Get database operation object ( Special execution sql Object of statement )
Step four : perform SQL sentence (DQL DML....)
Step five : Process query result set ( Only if the fourth step is select At the time of statement , The fifth step is to process the query result set .)
Step six : Release resources ( Be sure to close the resource after using it .Java And database belong to the communication between processes , Be sure to turn it off after you turn it on .)
2.JDBC Quick start
package com.aynu.jdbc;
import cn.aynu.pojo.User;
import java.sql.*;
/** * Inquire about tab_user surface */
public class JDBCTest04 {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet resultSet = null;
try {
// 1. Registration drive
Class.forName("com.mysql.jdbc.Driver");
// 2. Get the connection
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/db",
"root",
"root");
// 3. Get database operation object
stmt = conn.createStatement();
// 4. perform sql sentence
String sql = "select * from tab_user";
resultSet = stmt.executeQuery(sql);
// 5. Process query result set
User u = new User();
while (resultSet.next()){
String id = resultSet.getString("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
Date birthday = resultSet.getDate("birthday");
u.setId(id);
u.setName(name);
u.setAge(age);
u.setBirthday(birthday);
System.out.println(u);
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
// 6. Release resources
if (resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
Four 、 Detailed explanation JDBC Each object
1.DriverManager
DriverManager: Drive management objects
function :
1. Registration drive : Tell the driver of the corresponding database used by the program
Code :Class.forName("com.mysql.jdbc.Driver");
Source code analysis : stay com.mysql.jdbc.Driver Class has static code blocks
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
Be careful :mysql5 After the drive jar Packages can omit the steps of registering drivers .
2. Get database connection
Method :static Connection getConnection(String url, String user, String password)
Parameters :
url: Specify the path of the connection
grammar :jdbc:mysql://ip Address ( domain name ): Port number / Database name
Example :jdbc:mysql://localhost:3306/db
user: user name (mysql The user name of the database )
root: password (mysql Database password )
2.Connection
Connection: Database connection object
Access method :conn = DriverManager.getConnection(url, user, password);
function :
1. Access to perform sql Object of statement
conn.createStatement()
conn.prepareStatement(sql);
2. Manage affairs
Open transaction :conn.setAutoCommit(false);
Commit transaction :conn.commit();
Transaction rollback :conn.rollback();
Be careful : Here conn Generation refers to Connection object
3.Statement
Statement: perform sql The object of
Access method :Statement stmt = conn.createStatement();
1. perform sql
1. boolean execute(String sql) :
You can do whatever you want sql
2. int executeUpdate(String sql) :
It can be executed DML(insert、update、delete) sentence 、
DDL(create,alter、drop) sentence
* Return value : Number of rows affected , It can be judged by the number of rows affected DML Is the statement executed successfully
* Return value >0 Then the execution is successful , conversely , The failure .
3. ResultSet executeQuery(String sql) :
perform DQL(select) sentence
4.ResultSet
ResultSet: Result set object , Encapsulate query results
Access method :ResultSet resultSet = stmt.executeQuery(sql);
boolean next(): Move the cursor down one line , Determine whether the current line is the end of the last line ( Is there any data ),
If it is , Then return to false, If not, return true
* getXxx( Parameters ): get data
* Xxx: Representative data type Such as : int getInt() , String getString()
* Parameters :
1. int: Represents the number of the column , from 1 Start Such as : getString(1)
2. String: Name of representative column . Such as : getDouble("balance")
while (resultSet.next()){
// Get the data of this row in the database
String id = resultSet.getString("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
Date birthday = resultSet.getDate("birthday");
}
5. PreparedStatement
PreparedStatement: perform sql The object of ( Precompiled objects )
Access method :PrepareStatement pstmt = conn.prepareStatement(sql);
1. SQL Injection problem : In splicing sql when , Somewhat sql Special keywords participate in string splicing .
Can cause security problems
2 solve sql Injection problem : Use PreparedStatement Object to solve
2. precompiled SQL: Parameters use ? As placeholder
package com.aynu.jdbc;
import java.sql.*;
import java.util.Scanner;
/** * Practice using PreparedStatement * Implement login function id name */
public class JDBCTest05 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet resultSet = null;
try {
// 1. Registration drive
Class.forName("com.mysql.jdbc.Driver");
// 2. Get the connection
conn = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/day04",
"root", "root");
// 3. Get database operation object
// Definition sql sentence
String sql = "select * from tab_user where id = ? and name = ?";
pstmt = conn.prepareStatement(sql);
System.out.print("id:");
String id = new Scanner(System.in).nextLine();
System.out.print("name:");
String name = new Scanner(System.in).nextLine();
// to ? assignment
pstmt.setString(1, id);
pstmt.setString(2, name);
// 4. perform sql sentence
resultSet = pstmt.executeQuery();
// 5. Process query result set
if (resultSet.next()){
System.out.println(" Landing successful ");
} else{
System.out.println(" Login failed ");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 6. Release resources
if (resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null){
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
5、 ... and 、 Extract tool class
It is obvious from the above two code cases ,JDBC Code is not complicated , however Duplicate code A lot , So we need to extract a tool class , The following is a tool class I extracted in this stage of study , And configuration files ( take driver,url,user,password Extract a properties in ), You can also use it .
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=utf-8
user=root
password=root
Be careful : In daily study
?useUnicode=true&characterEncoding=utf-8user=root
To deal with the problem of Chinese garbled code
package com.aynu.util;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
/** * JDBC Tool class */
public class JDBCUtils {
private static String url;
private static String user;
private static String password;
private static String driver;
/** * Static code block , Used to load configuration files */
static {
try {
Properties pro = new Properties();
String path = Thread.currentThread().getContextClassLoader().getResource("jdbc.properties").getPath();
pro.load(new FileInputStream(path));
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
driver = pro.getProperty("driver");
// Registration drive
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/** * Get the connection * @return Connection object */
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
/** * Release resources * @param stmt * @param conn */
public static void close(Statement stmt, Connection conn){
if (stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/** * Release resources * @param rs * @param stmt * @param conn */
public static void close(ResultSet rs,Statement stmt, Connection conn){
if (rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
边栏推荐
- How to analyze the rising and falling rules of London gold trend chart
- Image 24 bit depth to 8 bit depth
- Win 11 major updates, new features love love.
- [combinatorics] generating function (generating function application scenario | using generating function to solve recursive equation)
- G1 garbage collector of garbage collector
- Bloom filter [proposed by bloom in 1970; redis cache penetration solution]
- Grammaire anglaise Nom - Classification
- Golang string (string) and byte array ([]byte) are converted to each other
- Use of unsafe class
- 2022-2028 global physiotherapy clinic industry research and trend analysis report
猜你喜欢
What is SQL get connection
Nodejs (01) - introductory tutorial
Why can deeplab v3+ be a God? (the explanation of the paper includes super detailed notes + Chinese English comparison + pictures)
Torch learning notes (7) -- take lenet as an example for dataload operation (detailed explanation + reserve knowledge supplement)
English语法_名词 - 分类
English grammar_ Adjective / adverb Level 3 - multiple expression
NFT new opportunity, multimedia NFT aggregation platform okaleido will be launched soon
Grammaire anglaise Nom - Classification
Sensor 调试流程
Theoretical description of linear equations and summary of methods for solving linear equations by eigen
随机推荐
Install apache+php+mysql+phpmyadmin xampp and its error resolution
[combinatorics] generating function (generating function application scenario | using generating function to solve recursive equation)
Three gradient descent methods and code implementation
Redis core technology and practice - learning notes (VII) sentinel mechanism
How many convolution methods does deep learning have? (including drawings)
圖像24比特深度轉8比特深度
PHP determines which constellation it belongs to today
Line by line explanation of yolox source code of anchor free series network (5) -- mosaic data enhancement and mathematical understanding
Software development freelancer's Road
Okaleido, a multimedia NFT aggregation platform, is about to go online, and a new NFT era may come
论文阅读 GloDyNE Global Topology Preserving Dynamic Network Embedding
Closure and closure function
Real time split network (continuous update)
ES7 - Optimization of promise
Gao Qing, Beijing University of Aeronautics and Astronautics: CIM is a natural quantum computing platform for graph data processing
Opencv learning notes (continuously updated)
[combinatorics] dislocation problem (recursive formula | general term formula | derivation process)*
[Tongxin UOS] scanner device management driver installation
[linux]centos 7 reports an error when installing MySQL "no package MySQL server available" no package ZABBIX server MySQL available
2022-2028 global physiotherapy clinic industry research and trend analysis report