当前位置:网站首页>JDBC knowledge
JDBC knowledge
2022-06-29 18:23:00 【Spirit Lord sinner】
One 、 know jdbc
jdbc What can ? What can be done
JDBC brief introduction - JDBC(Java DataBase Connectivity,java Database connection ) It's one for execution SQL Of the statement Java API, It can provide unified access for a variety of relational databases , It's used by a group Java Language written classes and interfaces .JDBC It provides a benchmark , From this, you can build more advanced tools and interfaces , Enable database developers to write database applications
For me ,jdbc It's a kind of toolbox encapsulated in a shelf bag
Commonly used tools
There are many common tools in this toolbox :
1. DriverManager – class : Used to obtain Connection
2. Connection – Interface ; Used to obtain Statement perhaps PreparedStatement Object's
3. Statement – Interface ; Used to perform sql Sentence method 1
4. PreparedStatement Interface : Used to perform sql Sentence method 2
5. ResultSet – Interface : Get the result set returned by executing the query statement
What's the use of these tools ?
First of all, we need to know this jdbc It's a tool , Connect java With the database , By means of java Direct operation database on program
-1、
This is not jdbc Of
The first one is : Suppose there is no jdbc This kind of APL Provide a unified operating language , So the application is operating MySql When using the database MySQL Special driver language , Use operation Oracle When you need it Oracle Database operation language , Besides, there are other databases , For a programmer , Spend too much time learning the language of other applications operating database Libraries , No doubt a waste of energy , and , Easy to confuse , The code is easy to couple , Deposition
-2、
There is jdbc Of
The second is , A is added in the middle Jdbc drive , In this set of drivers, there is a set of specialized and perfect language and interface to manage various databases , So , A set of programmer student numbers is enough , And liberate the application from direct contact with the database , This greatly reduces the coupling between the application and the database , Even when the application interfaces with other databases , It won't change much , Directly modifying jdbc Just fine
And what we need to learn is the second
Second, first download mysql Drive pack
open cmd Input :mysql -V
see mysql edition , there ’V’ It's in capital letters V
1, stay maven Warehouse downloading :dbc website : https://mvnrepository.com/artifact/mysql/mysql-connector-java
Then download the corresponding version of the rack package
–> After go in 
2. stay Official website Another method step downloaded in : Download from the official website
Import the downloaded rack package into
Create a new empty package , Choose a name at will ,lib
Import shelf package
Right click on the lib Folder , And then click add as library…
Jump out of this and click OK
such jdbc The environment is the first time
3、 ... and 、 Database connection steps
use jdbc Operating the data path is equivalent to turning the visual operation into a line of sorted code for operation
1. The load driver
A1、 Load driven in mysql6.0 The following versions use the following driver statements
Class.forName("com.mysql.jdbc.Driver");
A2、 After the update mysql6.0 For the above
Class.forName("com.mysql.cj.jdbc.Driver");
The original writing was :
DriverManager.registerDriver(new com.mysql.jdbc.Driver())
Because in Driver It encapsulates static code blocks , Once called, it will execute , If created in this way, it will be executed twice , So we don't advocate
The above line of code is equivalent to opening and loading the database >
2. User information and address
String url = "jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&usrSSL=true&serverTimezone=Asia/Shanghai";
String username = "root";
String userpassword = "123456";
For address url There are a lot of things to pay attention to :url Some introductions
jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&usrSSL=true&serverTimezone=Asia/Shanghai
jdbc:mysql:// : agreement
localhost: IP Address
3306: Port number
school: Database instance name
useUnicode=true&characterEncoding=utf8 Introduce :
usrSSL=true: Is the use of JDBC When connecting to your database , Yours JDBC Version and MySQL Version incompatible ,MySQL The version of is higher , Add... After the join statement “useSSL=‘true’” , You can connect to the database . Higher version .
serverTimezone=Asia/Shanghai: Set time zone , For Shanghai
“?”: Equivalent to a spliced character
“&”: amount to and
Format :
url=“ agreement :// This machine IP Address : Port number / Database name ”
Equivalent to the basic information of database application connection
Of course, databases are usually in their own mysql It's built inside , Even which database is up to you
3. Get database connection
Connection connection = DriverManager.getConnection(url, username, userpassword);

4. Create execution sql Of the statement statement object
Statement statement = connection.createStatement();

5. use statement Object to perform sql sentence
Be careful :
-1. Yes statement perform sql object
-2. Yes PreparedStatement perform sql object
There are two ways Related introduction
1 、 First there must be execution statements
String sql= "SELECT * FROM grade";
2 、 Created with statement Object to perform
ResultSet resultSet = statement.executeQuery(sql);
Yes
- statement.excuteQuery() : ( Inquire about ) After execution, a resultset
- statement.excute() : You can do anything sql sentence , Determine whether the first result is ResultSet object , If it is , be return true, Otherwise return to false
- statement.excuteUpdate() : ( Insert , to update . Delete ) Use this one to execute , A number of affected rows will be returned
6. Release resources
resultSet.close();
statement.close();
connection.close();
Close resources in order , It's equivalent to exiting in order mysql Visual interface for operation
Four 、jdbc Addition, deletion and modification of
use statement complete increase 、 Delete 、 Change 、 check
The following is a simplified addition, deletion, modification and query without packaging tools
1、 check yes select sentence
package Zer.demo.util;
import java.sql.*;
// My first one jdbc Program
public class Select {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1. The load driver
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());// Achieved two registrations
Class.forName("com.mysql.cj.dbc.Driver");
//2. Appliance information and address
String url = "jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai";
String username = "root";
String userpassword = "123456";
//3. Successful connection , Create database objects
Connection connection = DriverManager.getConnection(url, username, userpassword);
//4. Database object creation execution sq The object of , Write lost statements
Statement statement = connection.createStatement();
String sql= "SELECT * FROM grade";
//5、 Created with statement Object to perform sql sentence ,
ResultSet resultSet = statement.executeQuery(sql);// use executeQuery() Method , Will return a result set
while (resultSet.next()){
System.out.println("gradeid="+resultSet.getInt("gradeid"));
System.out.println("gradename="+resultSet.getString("gradename"));
System.out.println("………………………………………………………………………………………………………………………………………");
}
// System.out.println(i);
//6. Release the connection
resultSet.close();
statement.close();
connection.close();
}
}
2、 increase yes insert sentence
package Zer.demo.util;
import java.sql.*;
// My first one jdbc Program
public class Insert {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1. The load driver
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());// Achieved two registrations
Class.forName("com.mysql.cj.jdbc.Driver");
//2. Appliance information and address
String url = "jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai";
String username = "root";
String userpassword = "123456";
//3. Successful connection , Create database objects
Connection connection = DriverManager.getConnection(url, username, userpassword);
//4. Database object creation execution sq The object of , Write lost statements
Statement statement = connection.createStatement();
String sql= "insert into grade values(25,' How about this ')";
//5、 Created with statement Object to perform sql sentence ,
int i = statement.executeUpdate(sql);// For increment 、 Delete 、 Change , use executeUpdate() Method execution , Will return a number of affected rows
if (i>0){
System.out.println(" Insert the success ");
}else {
System.out.println(" Insert the failure ");
}
// System.out.println(i);
//6. Release the connection
statement.close();
connection.close();
}
}
3、 Change yes update sentence
package Zer.demo.util;
import java.sql.*;
// My first one jdbc Program
public class Update {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1. The load driver
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());// Achieved two registrations
Class.forName("com.mysql.cj.jdbc.Driver");
//2. Appliance information and address
String url = "jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai";
String username = "root";
String userpassword = "123456";
//3. Successful connection , Create database objects
Connection connection = DriverManager.getConnection(url, username, userpassword);
//4. Database object creation execution sq The object of , Write lost statements
Statement statement = connection.createStatement();// Perform the operation of the query
String sql= "update grade set gradename=' Everybody's the same , Even if it's different , It doesn't hurt to be a little tired ' where gradeid= 22";
//5、 Created with statement Object to perform sql sentence ,
int i = statement.executeUpdate(sql);// For increment 、 Delete 、 Change , use executeUpdate() Method execution , Will return a number of affected rows
if (i>0){
System.out.println(" The update is successful ");
}else {
System.out.println(" Update failed ");
}
// System.out.println(i);
//6. Release the connection
statement.close();
connection.close();
}
}
4、 Delete yes delete sentence
package Zer.demo.util;
import java.sql.*;
// My first one jdbc Program
public class Delete {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1. The load driver
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());// Achieved two registrations
Class.forName("com.mysql.cj.jdbc.Driver");
//2. Appliance information and address
String url = "jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai";
String username = "root";
String userpassword = "123456";
//3. Successful connection , Create database objects
Connection connection = DriverManager.getConnection(url, username, userpassword);
//4. Database object creation execution sq The object of , Write lost statements
Statement statement = connection.createStatement();
String sql= "delete from grade where gradeid =22";
//5、 Created with statement Object to perform sql sentence ,
int i = statement.executeUpdate(sql);// For increment 、 Delete 、 Change , use executeUpdate() Method execution , Will return a number of affected rows
if (i>0){
System.out.println(" Delete successful ");
}else {
System.out.println(" Delete failed ");
}
// System.out.println(i);
//6. Release the connection
statement.close();
connection.close();
}
}
Picture reference changed to
Connection made by tools
If you also find the law ,
Only :
1.sql Statement change
2. Execution time , The query is different from the addition, deletion and modification :(1) One is executeQuery() Return a result set , You can use while Circular display
(2) One is executeUpdate() Returns the number of affected rows , It can be used to judge whether the execution is successful
To this end, we can build a Tool class
https://blog.csdn.net/qq_45898383/article/details/118399812
5、 ... and 、SQL Injection problem
SQL A brief introduction
Use statement There is SQL Injection problem , There are security risks , So , If you want to know something about it, you can learn it by yourself
Computers have two languages :
1、 Interpretive language : When the computer is running , A running component interprets the running code , And execute the instructions contained therein ( Execute while parsing )
2、 Compiled language : When the code is generated, it is transformed into mechanical language , At run time, the instructions in the language are executed directly ( Direct execution )
In interpretative language : If the program interacts with the user . The user can construct special input to splice into the program to execute , So that the program executes according to the information entered by the user, and there may be malicious code .
Like this column
SQL After injection
1、SQL Injection gets more information
2、SQL Injection problems will lead to more information easy to leak
’or 1=1 – : One of the single quotes ’ In order to splice the previous user input information , parallel bars “–” An empty space can be followed by a comment . Don't comment , Parallel bars can not write
6、 ... and PreparedStatemen object
Can prevent SQL Injection and higher efficiency ,
about preparedstatement The object is :
- Multiple placeholders , Replace the original data with question marks “?”, Use a question mark to occupy a space
- Assign values manually , In the order of question marks , Assign values one by one from the first
1、 check
package Zer.demo.util1;
import java.sql.*;
public class Select1 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1. The load driver
Class.forName("com.mysql.cj.jdbc.Driver");
//2. User information
String url="jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai";
String username = "root";
String userpassword = "123456";
//3. Successful connection , Create database objects
Connection connection = DriverManager.getConnection(url, username, userpassword);
//4、 To write sql sentence
String sql= "select * from grade where gradeid = ? ";
//String sql= "select * from grade "; If there is no placeholder , You don't have to assign values , Just do it directly
//5. Precompile , Precompiled but not executed
PreparedStatement preparedStatement = connection.prepareStatement(sql);// Precompiled without execution
// After manual assignment , Will execute
preparedStatement.setInt(1,24);
//6. Execute the manually assigned statement
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
System.out.println(resultSet.getInt("gradeid"));
System.out.println(resultSet.getString("gradename"));
}
//7. Release resources
resultSet.close();
preparedStatement.close();
connection.close();
}
}
2、 increase
package Zer.demo.util1;
import java.sql.*;
public class Insert {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1. The load driver
Class.forName("com.mysql.cj.jdbc.Driver");
//2. User information
String url="jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai";
String username = "root";
String userpassword = "123456";
//3. Successful connection , Create database objects
Connection connection = DriverManager.getConnection(url, username, userpassword);
//4、 To write sql sentence
String sql= "insert into grade(gradeid,gradename) values(?,?)";
//5. Precompile , Precompiled but not executed
PreparedStatement preparedStatement = connection.prepareStatement(sql);// Precompiled without execution
// After manual assignment , Will execute
preparedStatement.setInt(1,27);
preparedStatement.setString(2," Do you still want to learn ");
//6. Execute the manually assigned statement
int i = preparedStatement.executeUpdate();// Returns the number of rows affected by an execution
if (i>0) {
System.out.println(" Insert the success ");
}else {
System.out.println(" Insert the failure ");
}
//7. Release resources
preparedStatement.close();
connection.close();
}
}
3、 Change
package Zer.demo.util1;
import java.sql.*;
public class Update1 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1. The load driver
Class.forName("com.mysql.cj.jdbc.Driver");
//2. User information
String url = "jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai";
String username = "root";
String userpassword = "123456";
//3. Successful connection , Create database objects
Connection connection = DriverManager.getConnection(url, username, userpassword);
//4、 To write sql sentence
String sql = "update grade set gradename = ? where gradeid = ? ";
//5. Precompile , Precompiled but not executed
PreparedStatement preparedStatement = connection.prepareStatement(sql);// Precompiled without execution
// After manual assignment , Will execute
preparedStatement.setString(1, " If you want to learn, of course you want to learn ");
preparedStatement.setInt(2, 27);
//6. Execute the manually assigned statement
int i = preparedStatement.executeUpdate();// Returns the number of rows affected by an execution
if (i > 0) {
System.out.println(" The update is successful ");
} else {
System.out.println(" Update failed ");
}
//7. Release resources
preparedStatement.close();
connection.close();
}
}
4、 Delete
package Zer.demo.util1;
import java.sql.*;
public class Delete1 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1. The load driver
Class.forName("com.mysql.cj.jdbc.Driver");
//2. User information
String url = "jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai";
String username = "root";
String userpassword = "123456";
//3. Successful connection , Create database objects
Connection connection = DriverManager.getConnection(url, username, userpassword);
//4、 To write sql sentence
String sql = "delete from grade where gradeid = ?";
//5. Precompile , Precompiled but not executed
PreparedStatement preparedStatement = connection.prepareStatement(sql);// Precompiled without execution
// After manual assignment , Will execute
preparedStatement.setInt(1,27);
//6. Execute the manually assigned statement
int i = preparedStatement.executeUpdate();// Returns the number of rows affected by an execution , The number of lines is greater than 0, Nature is success
if (i > 0) {
System.out.println(" Delete successful ");
} else {
System.out.println(" Delete failed ");
}
//7. Release resources
preparedStatement.close();
connection.close();
}
}
Tool class connection
preparedstatement The utility class simplifies the connection
Tool class :https://blog.csdn.net/qq_45898383/article/details/118399812
These are written by individuals at will , You guys, just take a look at it at will
边栏推荐
- 3H proficient in opencv (VI) - image stacking
- 回文子串的最大长度(字符串哈希+二分)
- 美法官裁定,被控掩盖黑客行为的Uber前安全主管必须面对欺诈指控
- DevCloud加持下的青软,让教育“智”上云端
- 3h精通OpenCV(八)-形状检测
- My first experience of remote office | community essay solicitation
- POJ 1975 (传递闭包)
- Adobe Premiere基础-不透明度(蒙版)(十一)
- Adobe Premiere foundation - sound adjustment (volume correction, noise reduction, telephone tone, pitch shifter, parameter equalizer) (XVIII)
- 等保测评结论为差,是不是表示等保工作白做了?
猜你喜欢

Servlet学生管理系统(萌新练手版)

JDBC Codes connexes

MySQL -connector/j driver download

Kubekey2.2.1 kubernetes1.23.7 offline package production +harbor Department summer and upload image

小白月赛51 补题 E G F

jdbc_相关代码

行程卡“摘星”热搜第一!刺激旅游产品搜索量齐上涨

NVIDIA installs the latest graphics card driver

DevCloud加持下的青软,让教育“智”上云端

mysql -connector/j驱动下载
随机推荐
Yolov6+tensorrt+onnx: deployment based on win10+tensorrt8+yolov6+onnx
Encryption and decryption of 535 tinyurl
3h精通OpenCV(七)-颜色检测
Image migration and data migration synchronization of old and new servers with different Alibaba cloud accounts
jdbc认识上手
Adobe Premiere foundation - cool text flash (14)
lodash深拷贝使用
[tcapulusdb knowledge base] tcapulusdb doc acceptance - create business introduction
Maximum length of palindrome substring (string hash + binary)
[how the network is connected] Chapter 3 explores hubs, switches and routers
Adobe Premiere Basics - general operations for editing material files (offline files, replacing materials, material labels and grouping, material enabling, convenient adjustment of opacity, project pa
Detailed analysis on the use of MySQL stored procedure loop
【TcaplusDB知识库】TcaplusDB单据受理-建表审批介绍
markdown知识轻轻来袭
Adobe Premiere基础-声音调整(音量矫正,降噪,电话音,音高换挡器,参数均衡器)(十八)
3h精通OpenCV(五)-透视变换
When easycvr deploys a server cluster, what is the reason why one is online and the other is offline?
【TcaplusDB知识库】TcaplusDB单据受理-事务执行介绍
Niuke small Bai monthly race 52 D ring insectivorous (feet +st table)
给定一个数在序列中求最大异或值(01字典)




SQL After injection 