当前位置:网站首页>JDBC - database connection
JDBC - database connection
2022-06-25 00:05:00 【Luo language】
List of articles
JDBC Introduce
JDBC Its full name is Java Database Connectivity, The literal translation is Java Database connection . It's used by a group Java Language written classes and interfaces . Different types of databases have corresponding implementations . We need to connect to the database , Go to the corresponding database official website to download the driver , All drives are based on jar The form of a package exists ,jar There are many in the bag .class file , these class The document is JDBC Interface implementation . This paper aims at MySQL Database connection implementation .
JDBC A six part series
- Registration drive ( effect : tell Java Program , Which brand database are you about to connect to ).
- Get the connection ( Express JVM The channel between the database process and the database process is opened , This belongs to communication between processes , A heavyweight , Close the channel after use )
- Get database operation object ( Special execution sql Object of statement ).
- perform sql sentence .
- Process query result set ( Only the fifth step is select At the time of statement , To get to this point ).
- Release resources ( Be sure to close the resource after using it ).
The complete code of database connection is as follows :
import java.sql.*;
public class JDBCTest06 {
public static void main(String[] args) {
Connection conn = null;
Statement state = null;
Driver driver = null;
ResultSet rs = null;
try {
/* Registration drive Here, ,Driver Object of type driver And the back of the com.mysql.cj.jdbc.Driver() Not one , They are under different packages . */
driver = new com.mysql.cj.jdbc.Driver();
DriverManager.registerDriver(driver);
/* The second step : Get the connection there url It's made up of : agreement :jdbc:mysql:// Database server ip Address : Because this machine is used here , So it says localhost Database port number :MySQL Private port number of :3306 Database account :root password :111111 */
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/study2","root","111111");
// Get database operation object
state = conn.createStatement();
/* perform sql sentence If you execute DML sentence (update,insert,delete), It is written as follows : state.executeUpdate("insert into user (id,name) value ("1", " Zhang San ")"); The following shows how to execute DQL sentence (select) */
rs = state.executeQuery("select *from user");
/* Process query results If rs Is there any access record in the ,next() Method returns true If the accessed field is varChar type , Then use getString(), If the access field is int type , Then use getInt(), If the access field is bigint, Then use getDouble(), The rest is the same . Note that there getStrng() And the parameters of methods of the same type , You can pass a field name , You can also transfer the subscript of the field to be queried ( from 1 Start ) */
while(rs.next()){
System.out.println(rs.getString(1) + " " + rs.getString(2));
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
// Release resources , To release from small to large
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(state != null){
try {
state.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
When registering the driver , We don't write that now , because com.mysql.cj.jdbc.Driver Class has the following static code block :
SQL Inject
Here we simply use the database to realize the login of an account .
public static boolean Login(String loginName, String passWord){
Connection conn = null;
Statement state = null;
ResultSet st = null;
try {
// Registration drive
Class.forName("com.mysql.cj.jdbc.Driver");
// Get the connection
conn = DriverManager.getConnection("jdbc:mysql://localhost/study2","root","111111");
// Get database operation object
state = conn.createStatement();
// Execute query statement
st = state.executeQuery("select *from login where loginName ='" + loginName + "'and loginPwd = '" + passWord + "'");
if(st.next()){
return true;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
if (state != null) {
try {
state.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
;
}
}
return false;
}
Here we use SQL Statement to achieve an account login function , among loginName, and passWordd Are entered by the user . If the user normally enters , for example : Input loginName by ’‘111’‘, Input passWord by ’‘12345678’', After splicing SQL The statement is as follows :
select * form login where loginName = '111' and passWord = '12345678'
As long as the name and password entered by the user are correct , There will be query results , Login successful .
If the user enters a with sql Keywords ’ Illegal information ’ And the illegal information string is changed sql The original meaning of the statement , As a result, the login is also successful if the correct information is not entered , for example : Input loginName by ’‘111’', Input passWord by ‘‘1' or ' 1' = '1’’, After splicing SQL The statement is as follows :
select * from login where loginName = '111' and passWord = '1' or '1' = '1';
If the user enters in this way, it will change SQL Original meaning of statement , As a result, the login is still successful without knowing the account and password , This is it. SQL Inject .
PerparedStatement
The use of Statement Object to perform sql Statement will cause SQL Injection problem ,Statement Subclasses of PreparedStatement Objects can be precompiled SQL sentence , Thus avoiding this problem .
Use PreparedStatement To implement a simple login as follows :
public static boolean login(String loginName, String passWord){
ResultSet rs = null;
Connection conn = null;
// Precompiled database operation object
PreparedStatement ps = null;
try {
// Registration drive
Class.forName("com.mysql.cj.jdbc.Driver");
// Connect to database
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/study2","root","111111");
// Get the precompiled database operation object
ps = conn.prepareStatement("select * from login where loginName = ? and loginPwd = ?");
// Pass values to the placeholder
ps.setString(1,map.get("loginName"));
ps.setString(2,map.get("passWord"));
// perform sql sentence
rs = ps.executeQuery();
// Process query results
if(rs.next()){
return true;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return false;
}
In this method, we call the database connection object prepareStatement(sql) Method to obtain the precompiled database operation object , When obtaining the precompiled database operation object, you need to pass in SQL Frame of statement , Where it uses placeholders ? Instead of sql Statement to receive values . And then we use setString(int parameterIndex, String x) Method to a placeholder ‘ ?’ Pass value .
Statement And PreparedStatement Compare
- Statement There is sql Injection problem ,PreparedStatement non-existent sql Injection problem .
- Statement Every execution needs to be performed on sql Statement to compile once , Low efficiency ,PreparedStatement You only need to compile once to execute N Time , More efficient .
- PreparedStatement Type checking will be done at the compilation stage , however Statement Can't .
- PreparedStatement Does not support sql Statement splicing ,Statement More flexible .
JDBC Transaction mechanism of
- JDBC Transactions in are automatically committed . Just execute one DML sentence , Will be automatically submitted once .
- if conn Connect objects for the database , Call the following methods to perform related transaction operations .
// Turn off auto submit
conn.setAutoCommit(false);
// Roll back the transaction
conn.rollback();
// Commit transaction
conn.commit();
边栏推荐
- 中低速航空航天电子总线概述
- 从数字化过渡到智能制造
- 信号完整性(SI)电源完整性(PI)学习笔记(二十五)差分对与差分阻抗(五)
- Go shopping
- VR全景怎么赚钱?结合市场从两个方面客观分析下
- openGauss内核:简单查询的执行
- Andersen global strengthens the Middle East platform with Palestinian member companies
- Fast pace? high pressure? VR panoramic Inn brings you a comfortable life
- Hello C (VII) - structure
- Analysis report on operation trend and investment strategy of global and Chinese tetrahydrofurfuryl propionate industry from 2022 to 2028
猜你喜欢

canvas螺旋样式的动画js特效

Dynamic effect of canvas lines

【排行榜】Carla leaderboard 排行榜 运行与参与手把手教学

Do280openshift access control -- encryption and configmap

离散数学及其应用 2018-2019学年春夏学期期末考试 习题详解

QT display RGB data

Using ADC to control brushless motor source program STM32 library function

MySQL problem points

美国众议院议员:数字美元将支持美元作为全球储备货币

MySQL日志管理
随机推荐
Collective例子
canvas线条的动态效果
svg+js键盘控制路径
QT cannot be edited with UTF-8
有趣的checkbox计数器
QT display RGB data
磁带svg动画js特效
颜色渐变梯度颜色集合
为什么生命科学企业都在陆续上云?
C程序设计专题 15-16年期末考试习题解答(上)
第三代电力电子半导体:SiC MOSFET学习笔记(五)驱动电源调研
Scala IO serialization and deserialization
C# Winform 最大化遮挡任务栏和全屏显示问题
技术分享| WVP+ZLMediaKit实现摄像头GB28181推流播放
Scala IO case
Hello C (III) - pointer
Today's sleep quality record 79 points
Analysis report on development mode and investment direction of sodium lauriminodipropionate in the world and China 2022 ~ 2028
Tutorial details | how to edit and set the navigation function in the coolman system?
MySQL日志管理