当前位置:网站首页>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();
边栏推荐
- Scala IO reads data from URLs and other data sources
- Hibernate learning 2 - lazy loading (delayed loading), dynamic SQL parameters, caching
- 节奏快?压力大?VR全景客栈带你体验安逸生活
- 颜色渐变梯度颜色集合
- 时间统一系统
- 无人驾驶: 对多传感器融合的一些思考
- im即时通讯开发应用保活之进程防杀
- Creative SVG ring clock JS effect
- Outer screen and widescreen wasted? Harmonyos folding screen design specification teaches you to use it
- Tape SVG animation JS effect
猜你喜欢

Using ADC to control brushless motor source program STM32 library function

Tiktok actual combat ~ sorting out the short video release process

颜色渐变梯度颜色集合

Hello C (III) - pointer

信号完整性(SI)电源完整性(PI)学习笔记(二十五)差分对与差分阻抗(五)

Creative SVG ring clock JS effect

Svg line animation background JS effect

怎么把wps表格里某一列有重复项的整行删掉

无人驾驶: 对多传感器融合的一些思考

How to delete the entire row with duplicate items in a column of WPS table
随机推荐
Analysis report on the development trend and Prospect of cetamide industry in the world and China from 2022 to 2028
Svg line animation background JS effect
Global and Chinese tetrahydrofurfuryl butyrate industry operation pattern and future prospect report 2022 ~ 2028
中低速航空航天电子总线概述
Im instant messaging development application keeping alive process anti kill
Report on operation pattern and future prospect of global and Chinese propyl isovalerate industry from 2022 to 2028
Technology sharing | wvp+zlmediakit realizes streaming playback of camera gb28181
JPA learning 1 - overview, JPA, JPA core annotations, JPA core objects
JDBC —— 数据库连接
JPA学习2 - 核心注解、注解进行增删改查、List查询结果返回类型、一对多、多对一、多对多
Analysis report on operation pattern and supply and demand situation of global and Chinese cyano ketoprofen industry from 2022 to 2028
The file containing the file operation vulnerability (6)
Development status and prospect trend forecast report of humic acid sodium industry in the world and China from 2022 to 2028
Collective example
Fast pace? high pressure? VR panoramic Inn brings you a comfortable life
Hibernate学习3 - 自定义SQL
Outer screen and widescreen wasted? Harmonyos folding screen design specification teaches you to use it
【排行榜】Carla leaderboard 排行榜 运行与参与手把手教学
Ansible及playbook的相关操作
Analysis report on operation trend and investment strategy of global and Chinese tetrahydrofurfuryl propionate industry from 2022 to 2028