当前位置:网站首页>JDBC details
JDBC details
2022-07-06 19:20:00 【Gentle ~】
Recommended reading :Druid Database connection pool
List of articles
Quick start
Java The process of operating the database
1. To write Java Code ;
2.Java Code will SQL Send to MySQL Server side ;
3.MySQL The server receives SQL Statement and execute the SQL sentence ;
4. take SQL The result of statement execution is returned to Java Code ;
JDBC Specific implementation process
1. Create a project , Import driver jar package ;
2. Registration drive :Class.forName("com.mysql.jdbc.Driver");
3. Get the connection : Connection conn = DriverManager.getConnection(url, username, password);Java The code needs to be sent SQL to MySQL Server side , You need to establish a connection first ;
4. Definition SQL sentence :String sql = “update…” ;;
5. Access to perform SQL object : perform SQL Sentence needs SQL Perform object , And the execution object is Statement object ,Statement stmt = conn.createStatement();
6. perform SQL:stmt.executeUpdate(sql);
7. Processing return results ;
8. Release resources ;
API Detailed explanation
DriverManager Get the connection
Registration drive
DriverManager( Driver management ) effect : Registration drive ;
stay Java In the document static void registerDriver(Driver driver) Method is used to register drivers .
Inquire about MySQL Provided Driver class , You can see that this method is implemented in static code blocks . The code is as follows :
In the static code block in this class DriverManager Object's registerDriver() Method to register the driver , Then we just need to load Driver class , The static code block will execute . and Class.forName("com.mysql.jdbc.Driver"); It can be loaded Driver class .
So before connecting to the database , We just need to execute the following code .
Class.forName("com.mysql.jdbc.Driver");
Be careful
MySQL 5 Later driver package , You can omit the steps of registering the driver , It will automatically load jar In bag META-INF/services/java.sql.Driver Driver class in file .
Get database connection
static Connection getConnection(String url, String user, String password)
Parameter description
url: Connection path
grammar :jdbc:mysql://ip Address ( domain name ): Port number / Database name ? Parameter key value pair 1& Parameter key value pair 2…
Example :jdbc:mysql://127.0.0.1:3306/db1
* If the connection is local mysql The server , also mysql The default port for the service is 3306, be url I could just write it as :jdbc:mysql:/// Database name ? Parameter key value pair
* To configure useSSL=false Parameters , Disable secure connection mode , Resolve warning tips
user: user name
poassword : password
Code example
public class connect {
public static void main(String[] args) throws Exception {
// MySQL 5 Later driver package , You can omit the steps of registering the driver
// Class.forName("com.mysql.jdbc.Driver");
String url="jdbc:mysql://127.0.0.1:3306/sd?useSSL=false";
String user="root";
String password="root";
try {
Connection conn= DriverManager.getConnection(url,user,password);
System.out.println(" Successful connection !");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
Connection Get objects
Access to perform SQL The object of
1. Common execution SQL object
Statement createStatement()
2. precompile SQL Implementation SQL object : prevent SQL Inject
PreparedStatement prepareStatement(sql)
This method is commonly used , Can prevent SQL Inject , It will be explained in detail later in this article .
3. The object that executes the stored procedure
CallableStatement prepareCall(sql)
Obtained in this way CallableStatement Execution objects are used to execute stored procedures , But stored procedures are MySQL It's not often used in English .
Code example
public class connect {
public static void main(String[] args) throws Exception {
// MySQL 5 Later driver package , You can omit the steps of registering the driver
// Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://127.0.0.1:3306/sd?useSSL=false";
String user = "root";
String password = "root";
Connection conn = DriverManager.getConnection(url, user, password);
String sql="update course set cname='C++' where cno=1";
Statement stmt=conn.createStatement();
int count=stmt.executeUpdate(sql);
System.out.println(count);
}
}
Business management
Open transaction : BEGIN; perhaps START TRANSACTION;
Commit transaction : COMMIT;
Roll back the transaction :ROLLBACK;
MySQL The default is to automatically commit transactions
Open transaction
void setAutoCommit(boolean autoCommit)
Participate in autoCommit Indicates whether the transaction is automatically committed ,true Represents an automatic commit transaction ,false Indicates that the transaction is committed manually . To start a transaction, you need to set this parameter to false.
Commit transaction
void commit()
Roll back the transaction
void rollback()
Code example
public class connect {
public static void main(String[] args) throws Exception {
// MySQL 5 Later driver package , You can omit the steps of registering the driver
// Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://127.0.0.1:3306/sd?useSSL=false";
String user = "root";
String password = "root";
Connection conn = DriverManager.getConnection(url, user, password);
String sql1="update course set cname='Java' where cno=1";
String sql2="update course set cname='Java' where cno=2";
Statement stmt=conn.createStatement();
try {
int count1=stmt.executeUpdate(sql1);
System.out.println(count1);
int i=1/0; // Man made anomalies , To observe the return roll operation
int count2=stmt.executeUpdate(sql2);
System.out.println(count2);
// If there is no abnormality , Then submit all changes , Database update
conn.commit();
} catch (SQLException e) {
// If there are anomalies , Then undo all previous operations (sql1 Update operation for )
conn.rollback();
}
}
}
Statement Execute statement
Statement Object is used to execute SQL sentence . And for different types of
SQL Statements use different methods .
perform DDL、DML sentence :executeUpdate
int executeUpdate(String sql)
perform DQL sentence :executeQuery
ResultSet executeQuery(String sql)
This method involves ResultSet object , It will be explained in detail later in this article .
Code example
public class connect {
public static void main(String[] args) throws Exception {
// MySQL 5 Later driver package , You can omit the steps of registering the driver
// Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://127.0.0.1:3306/sd?useSSL=false";
String user = "root";
String password = "root";
Connection conn = DriverManager.getConnection(url, user, password);
String sql1 = "update st set age=15 where name='Tom'";
String sql2 = "select * from st";
Statement stmt = conn.createStatement();
// perform DDL、DML sentence
int c = stmt.executeUpdate(sql1);
System.out.println(c);
System.out.println("------------------");
// perform DQL sentence : Inquire about
ResultSet rs = stmt.executeQuery(sql2);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println(id + " " + name + " " + age);
}
}
}
Running results 
ResultSet Processing return results
summary
ResultSet Encapsulates the SQL The result of the query statement , Yes DQL Statement will return the object .
ResultSet executeQuery(String sql)
ResultSet Object provides methods to manipulate query result data , as follows :
| Method | explain |
|---|---|
| boolean next() | Move the cursor down one line and judge whether the new line is valid ,true It works 、false Invalid |
get data Xxx getXxx( Parameters );Xxx: The data type to query , Such as getInt( Parameters ); Parameters :
If you query with the name of the column, it is passed to String type , Such as getString("name");
If you use the index of the column to query , Pass on int type , The index of the first column of the table is 1, Such as getString(1);
Code example
public class connect {
public static void main(String[] args) throws Exception {
// MySQL 5 Later driver package , You can omit the steps of registering the driver
// Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://127.0.0.1:3306/sd?useSSL=false";
String user = "root";
String password = "root";
Connection conn = DriverManager.getConnection(url, user, password);
String sql = "select * from st";
Statement stmt = conn.createStatement();
System.out.println("--------- Query with the name of the column ----------");
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println(id + " " + name + " " + age);
}
System.out.println("--------- Use the index of the column to query ----------");
ResultSet rs1 = stmt.executeQuery(sql);
while (rs1.next()) {
int id = rs1.getInt(1);
String name = rs1.getString(2);
int age = rs1.getInt(3);
System.out.println(id + " " + name + " " + age);
}
}
}

PreparedStatement Anti Injection
PreparedStatement effect : precompile SQL Statement and execute , The prevention of SQL Injection problem . It is achieved by escaping special characters .
obtain PreparedStatement object
PreparedStatement prepareStatement(String sql)
// SQL Parameter value in statement , Use ? Placeholder replacement
String sql = "select * from user where username = ? and password = ?";
// adopt Connection Object acquisition , And pass in the corresponding sql sentence
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1,"user");
pstmt.setInt(2,123456);
Set the parameter value
PreparedStatement object :setXxx( Parameters , value ): to ? assignment
Xxx: data type ; Such as setInt(1,10);
Parameters :? Location number of , from 1 Start ;
** value :** The value assigned to the parameter
perform SQL sentence
call executeUpdate() and executeQuery() These two methods do not need to be passed SQL sentence , Because get SQL Statement has been executed on SQL The sentence is precompiled .
public void testPreparedStatement() throws Exception {
//2. Get the connection : If the connection is local mysql And the port is the default 3306 Can simplify writing
String url = "jdbc:mysql:///db1?useSSL=false";
String username = "root";
String password = "1234";
Connection conn = DriverManager.getConnection(url, username, password);
// Receive user input User name and password
String name = "zhangsan";
String pwd = "' or '1' = '1";
// Definition sql
String sql = "select * from tb_user where username = ? and password = ?";
// obtain pstmt object
PreparedStatement pstmt = conn.prepareStatement(sql);
// Set up ? Value
pstmt.setString(1,name);
pstmt.setString(2,pwd);
// perform sql
ResultSet rs = pstmt.executeQuery();
// Judge whether the login is successful
if(rs.next()){
System.out.println(" Login successful ~");
}else{
System.out.println(" Login failed ~");
}
//7. Release resources
rs.close();
pstmt.close();
conn.close();
}
边栏推荐
- C#/VB. Net to add text / image watermarks to PDF documents
- Leetcode topic [array] - 119 Yang Hui triangle II
- openmv4 学习笔记1----一键下载、图像处理背景知识、LAB亮度-对比度
- 打家劫舍III[后序遍历与回溯+动态规划]
- [translation] a GPU approach to particle physics
- 业务与应用同步发展:应用现代化的策略建议
- pychrm社区版调用matplotlib.pyplot.imshow()函数图像不弹出的解决方法
- 应用使用Druid连接池经常性断链问题分析
- 反射及在运用过程中出现的IllegalAccessException异常
- Elastic search indexes are often deleted [closed] - elastic search indexes gets deleted frequently [closed]
猜你喜欢
![打家劫舍III[后序遍历与回溯+动态规划]](/img/9b/e9eeed138e46afdeed340bf2629ee1.png)
打家劫舍III[后序遍历与回溯+动态规划]

A method of removing text blur based on pixel repair

黑馬--Redis篇
![[paper notes] transunet: transformers make strongencoders for medical image segmentation](/img/21/3d4710024248b62495e2681ebd1bc4.png)
[paper notes] transunet: transformers make strongencoders for medical image segmentation
![[depth first search] Ji suanke: find numbers](/img/e4/708a1e8252bcd2d0d621c66bf6bfed.jpg)
[depth first search] Ji suanke: find numbers

C language daily practice - day 22: Zero foundation learning dynamic planning

三面蚂蚁金服成功拿到offer,Android开发社招面试经验

If you have any problems, you can contact me. A rookie ~

CCNP Part 11 BGP (III) (essence)

pychrm社区版调用matplotlib.pyplot.imshow()函数图像不弹出的解决方法
随机推荐
QPushButton绑定快捷键的注意事项
PMP每日一练 | 考试不迷路-7.6
[translation] a GPU approach to particle physics
反射及在运用过程中出现的IllegalAccessException异常
tensorflow和torch代码验证cuda是否安装成功
About NPM install error 1
Excel 中VBA脚本的简单应用
pytorch常见损失函数
包装行业商业供应链管理平台解决方案:布局智慧供应体系,数字化整合包装行业供应链
R语言使用order函数对dataframe数据进行排序、基于单个字段(变量)进行降序排序(DESCENDING)
Helm deploy etcd cluster
Precautions for binding shortcut keys of QPushButton
A full set of teaching materials, real questions of Android interview of 7 major manufacturers including Alibaba Kwai pinduoduo
Help improve the professional quality of safety talents | the first stage of personal ability certification and assessment has been successfully completed!
C # - realize serialization with Marshall class
基于蝴蝶种类识别
MRO industrial products enterprise procurement system: how to refine procurement collaborative management? Industrial products enterprises that want to upgrade must see!
Mathematical knowledge -- code implementation of Gaussian elimination (elementary line transformation to solve equations)
Airiot IOT platform enables the container industry to build [welding station information monitoring system]
If you have any problems, you can contact me. A rookie ~