当前位置:网站首页>JDBC and MySQL database
JDBC and MySQL database
2022-07-04 09:35:00 【Drink ice for ten years】
load MYSQL Database driven
The development tool used by the author is IntelliJ IDEA, Other integration environments have similar principles .
download MYSQL Database driven
JDBC namely (Java Data Base Connectivity), Applications in order to access MYSQL Database on the database server , It must be ensured that the corresponding JDBC-MYSQL drive . You can go to the official website :www.mysql.com download , You can also use me to download good mysql drive .
1. Log in to the official website www.mysql.com after , Select... On the navigation bar of the page Products
2. In the right area of the page MySQL Features Choose MYSQL Connectors
3. In the right area of the page Developed by MySQL Choose JDBC Driver for MySQL(Connector/J)
4. Or you can use the driver I downloaded mysql-connector-java-5.1.40-bin.jar
link :https://pan.baidu.com/s/1XEwVXKilL9Hc7Tjhl5xXGA
Extraction code :5zrb
Import MYSQL Database driven
1. Click on File->Project Structure
2. Click on Modulus、 Click on Dependencies 、 Click on + Number 、 Click on JARs or directories, Then select the database driver just downloaded
3. After importing successfully ,External Libraries See this driver in
load MYSQL Database driven
The application is responsible for loading JDBC-MYSQL The database driven code is as follows , Use try-catch Statement is because there may be exceptions, and the loading is unsuccessful
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(Exception e){
}
Connect MYSQL database
Connect MYSQL There are two ways to build a database , among getConnction() Is an overloaded method .
The first connection
The database connection object can only be used Connection To declare , Out of commission new To get . To get the database connection object , You have to use JDBC Provided API: Drive managers DriverManager Call its methods getConnection(url) To get . as follows :
Connection con = DriverManager.getConnection(String url);
among url The format is :
String url = "jdbc:mysql://localhost:3306/xsxk?user=root&password=root&userSSL=true&characterEncoding=utf-8";
1、localhost: This is the host of the database you want to connect to IP Address , If it is on this machine, use localhost
2、3306: This is mysql The port number used by the database , because 3306 yes MYSQL The default port number of the database server , Allow applications to omit the default port number when connecting to the database
3、xsxk: This is the name of the database you want to connect to , What I am connecting here is a computer named xsxk The database of .
4、user=root: This is the user name that has access to the database , My user name is root
5、password=root: This is the password corresponding to the user name , The password I use is root
6、useSSL=true:MYSQL5.6 Version above can be written, but not written ,5.6 Later versions must be written ;useSSL namely :use Secure Socket Link, Use secure socket connection
7、characterEncoding=utf-8: If the record of the table in the database has Chinese characters , Then you must pass an additional parameter when establishing the connection characterEncoding, And take the value gb2312 or utf-8
The second way to connect
The second connection method is more brief , That is to change the account number and password from URL Split it out , Passed as two parameters to getConnection(String url,String user,String passeord) function , as follows :
Connextion con;
String url = "jdbc:mysql://localhost:3306/xsxk?userSSL=true";
String user = "root";
String password = "root";
try{
con = DriverManager.getConnection(url,user,password);
}catch(SQLException e){
}
Query operation
send out SQL sentence
1. get SQL Statement object
SQL Statement objects can only be used Statement To declare , Not available new To generate , You need to use the database connection object obtained above to call its method createStatement() To obtain a , as follows :
try{
Statement sql = con.createStatement();
}catch(SQLException e){
}
2. send out sql sentence
sql Statement object calls method executeQuery(“String sql”), send out SQL Query statement .
And return a result set Resultset, The following is to a man named students Send query request to the table of :
ResultSet rs = sql.executeQuery("SELECT * FROM students");
Process query results
ResultSet Object can only see one data row at a time , Use next() Method moves to the next line , After obtaining a row of data ,ResultSet Object can be used getXxx() Method to get the field value , Function parameters can be either field names or columns represented by Arabic numerals , Such as getInt(“name”) or getInt(1). It is worth noting that ,ResultSet The initial position of the object is in front of the first row of the result set
ResultSet Some methods to solve this problem
Return type Method name
boolean next()
byte getByte(int columnIndex)// Column number representation
Date getDate(int columnIndex)
double getDouble(int columnIndex)
float getFloat(int columnIndex)
int getInt(int columnIndex)
long getLong(int columnIndex)
String getString(int columnIndex)
byte getByte(String columnName)// Field name
Date getDate(String columnName)
double getDouble(String columnName)
float getFloat(String columnName)
int getInt(String columnName)
long getLong(String columnName)
String getString(String columnName)
Close the connection
JDBC The use of Mapping technology, not replication , For the results of the query , Mapping to ResultSet in , It's like looking in a mirror , Instead of copying . That means Resuluset Object and database connection object realize close binding , Once the connection object is closed ,ResultSet The data in immediately disappears . So we're using ResultSet When data in , You must always maintain a connection to the database , Until it is used up ResultSet Data in , So call after using the data con.close().
Example of sequential query
The so-called sequential query , Refer to resultSet Object can only see one data row at a time , Use next Method to move to the next data row , The following example is a query xsxk( Students' course selection ) In the database xsb( Student list ) Of name Value of field
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Example {
public static void main(String[] args) {
Connection con = null;// Database connection object
Statement sql;//SQL Statement object
ResultSet re;// Result set object
try{
Class.forName("com.mysql.jdbc.Driver");// load JDBC-MYSQL drive
}
catch (Exception e){
System.out.println(" Loading failed ");// exception handling
}
String uri = "jdbc:mysql://localhost:3306/xsxk?useSSL=true";// Of the database to be accessed URL
String user = "root";// User name authorized to access the database
String password = "root";// The password corresponding to the user name
try{
con = DriverManager.getConnection(uri,user,password);// Obtain a connection
}
catch (Exception e){
System.out.println(" Connection acquisition failed ");// exception handling
}
try{
sql = con.createStatement();// get SQL Statement object
re = sql.executeQuery("SELECT * FROM xsb");// Perform query operation
while(re.next()){
String xuehao = re.getString(1);// Check the value of the first column ( Student number )
String number = re.getString("xm");// see xm Value of field ( full name
System.out.print(xuehao);// Output the student number queried
System.out.println(" "+number);// Output the queried name
}
con.close();// After using the data , Close the connection
}
catch (Exception e){
System.out.println(e);
}
}
}
The result of the query is consistent with the data in the database , Here's the picture :
Cursor query example
The cursor position of the result set is above the first row , Use next() Method to view data becomes a sequential query . If you want to directly obtain the data of a row in the result set , You need to get a scrollable result set , In use for this purpose con.createStatement() When the method is used , We need to make corresponding changes , As shown below :
Statement sql = con.createStatement(int type,int concurrency);
1.type The value of determines the scrolling mode , The values are as follows :
1)ResultSet.TYPE.FORWORD_ONLY: The cursor of the result set can only move down
2)ResultSet.TYPE.SCROLL_INSENSITIVE: The cursor of the result set can be moved up and down , When the database changes , The current result set remains unchanged
3)ResultSet.TYPE.SCROLL_SENSITIVE: The cursor of the result set can be moved up and down , When data changes , The current result set changes synchronously
2.concurrent The value of determines whether the database can be updated with the result set , The values are as follows :
ResultSet.CONCUR.READ_ONLY: You cannot update a table in a database with a result set
ResultSet.CONCUR.UPDATEBLE: The result set can be used to update the tables in the database
3. When using cursor query , Often used to ResultSet The following methods of :
public boolean previous(); // Move the cursor up , Return when moving before the first line false
public void beforeFirst(); // Move the cursor to the initial position of the result set , That is, before the first line
public void afterLast(); // Move the cursor after the last row of the result set
public void first(); // Move the cursor to the first row of the result set
public void last(); // Move the cursor to the last row of the result set
public boolean isAfterLast(); // Determine whether the cursor is after the last line
public boolead isBeforeFirst(); // Determine whether the cursor is before the first line
public boolean isFirst(); // Determine whether the cursor is on the first line
public boolean isLast(); // Determine whether the cursor is on the last line
public int getRow(); // Get the line number pointed by the current cursor , Line number from 1 Start coding , If the result set has no rows , return 0
public boolean absolute(int row);
// Move cursor to parameter row Specified row , If row A negative number is the line that represents the reciprocal ,absolute Move to the last line ,absolute(-2) Move to the penultimate line , When moving to the front of the first line or after the last line is , This method returns false.
The following example first moves the cursor to the last line , Get the total number of records in the student form , Then move the cursor to the 15 That's ok , Get the second 15 The name of the student who is ok
package Example11;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Example {
public static void main(String[] args) {
Connection con = null;
Statement sql;
ResultSet re;
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch (Exception e){
System.out.println(" load JDBC Failure ");
}
String uri = "jdbc:mysql://localhost:3306/xsxk?useSSL=true";
String user = "root";
String password = "root";
try{
con = DriverManager.getConnection(uri,user,password);
}
catch (Exception e){
System.out.println(" The connection fails ");
}
try{
sql = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
re = sql.executeQuery("SELECT * FROM xsb");
re.last();// Move the cursor to the last line
int max = re.getRow();
System.out.println(" There are altogether "+max+" Record ");
re.absolute(15);
String name = re.getString("xm");
System.out.println(" The first 15 The name of the student who is OK is :"+name);
con.close();
}
catch (Exception e){
System.out.println(e);
}
}
}
The running result corresponds to the data of the table in the database
to update 、 Add and delete operations
Statement Object calls the following methods , Through parameters sql Update the database 、 Add and delete operations :
public int executeUpdate(String sql);
Following example , Realized
Insert A group called “ Zhang San ” The record of
to update A group called “ Zhang Zhang ” The record of is “ Chen Chen ”
Delete I got a new one called “ Li Si ” The record of
package Example11;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Example11_4 {
public static void main(String[] args) {
Connection con = null;
Statement sql;
String url="jdbc:mysql://localhost:3306/xsxk?useSSL=true&characterEncoding=utf-8";
String user="root";
String password = "root";
try{
Class.forName("com.mysql.jdbc.Driver");
}catch (Exception E){
System.out.println(" load JDBC Failure ");
}
try{
con = DriverManager.getConnection(url,user,password);
}catch (Exception e){
System.out.println(" The connection fails ");
}
try{
sql = con.createStatement();
sql.executeUpdate("insert into try values (3,' Zhang San ')");
sql.executeUpdate("update try set name = ' Chen Chen ' where id = 1 ");
sql.executeUpdate("delete from try where name=' Li Si '");
con.close();
}catch(Exception e){
System.out.println(" operation failed ");
}
}
}
The table record before operation is :
The table record after operation is :
Use preprocessing statements
Java It provides a more efficient database operation mechanism , Namely PreparedStatement object , This object is customarily called a preprocessing statement object
1. Advantages of preprocessing statements
Send a to a database SQL sentence , for example select * from try, In the database SQL The interpreter is responsible for SQL Statement generates the underlying internal commands , Then execute the command , Complete the relevant operations . If you constantly submit to the database SQL sentence , It is bound to increase the number of SQL Interpreter burden , Affect the speed of execution . If the application can target the connected database , Implementation will SQL Statements are interpreted as internal commands at the bottom of the database , Then directly let the database execute this command , Obviously, it not only reduces the burden of the database , And it also improves the speed of accessing the database .
about JDBC for , If used Connection Establish a connection object with a database con, that con You can call preparedStatement(String sql) Method on parameter sql Pre compile the specified statement , Get a preprocessing statement object .
2. Use wildcards
In the face of SQL Statement preprocessing , You can use wildcards ?( English question mark ) To replace the value of the field , However, the specific value represented by the wildcard must be set before the preprocessing object is executed .
The following example represents the first wildcard ? The value represented is “ Zhang San ”, The second wildcard ? The value represented is “ Li Si ”:
sql.setString(1," Zhang San ");
sql.setString(2," Li Si ");
Set wildcards when using preprocessing statement objects ? The value of , Common methods are
void setDate(int preparedIndex,Date x);
void setDouble(int preparedIndex,Double x);
void setFloat(int preparedIndex,Float x);
void setInt(int preparedIndex,Int x);
void setLong(int preparedIndex,Long x);
void setString(int preparedIndex,String x);
The following example uses wildcards to insert a sequence number 100, be known as “ Use wildcards ” The record of
package Example11;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class Example11_5 {
public static void main(String[] args) {
Connection con = null;
String url = "jdbc:mysql://localhost:3306/xsxk?useSSL=true&characterEncoding=utf-8";
String user = "root";
String password = "root";
PreparedStatement sql;
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(Exception e){
System.out.println(" Loading failed ");
}
try{
con = DriverManager.getConnection(url,user,password);
}catch(Exception e){
System.out.println(" The connection fails ");
}
try{
sql = con.prepareStatement("insert into try values(?,?)");
sql.setInt(1,100);
sql.setString(2," Use wildcards ");
sql.executeUpdate();
con.close();
}catch(Exception e){
System.out.println(" operation failed ");
}
}
}
The results are shown in the following figure :
边栏推荐
- Flutter tips: various fancy nesting of listview and pageview
- If you can quickly generate a dictionary from two lists
- 《网络是怎么样连接的》读书笔记 - 认识网络基础概念(一)
- After unplugging the network cable, does the original TCP connection still exist?
- MySQL transaction mvcc principle
- 《网络是怎么样连接的》读书笔记 - FTTH
- Global and Chinese market of air fryer 2022-2028: Research Report on technology, participants, trends, market size and share
- Review of last week's hot spots (6.27-7.3)
- GoLand environment variable configuration
- Explanation of for loop in golang
猜你喜欢
PHP is used to add, modify and delete movie information, which is divided into foreground management and background management. Foreground users can browse information and post messages, and backgroun
mmclassification 标注文件生成
Mantis creates users without password options
2022-2028 global elastic strain sensor industry research and trend analysis report
Web端自动化测试失败原因汇总
Daughter love in lunch box
26. Delete duplicates in the ordered array (fast and slow pointer de duplication)
Explain TCP protocol in detail three handshakes and four waves
回复评论的sql
法向量点云旋转
随机推荐
回复评论的sql
About the for range traversal operation in channel in golang
2022-2028 global optical transparency industry research and trend analysis report
Launpad | 基础知识
Write a jison parser (7/10) from scratch: the iterative development process of the parser generator 'parser generator'
Lauchpad X | 模式
Write a jison parser from scratch (2/10): learn the correct posture of the parser generator parser generator
Implementing expired localstorage cache with lazy deletion and scheduled deletion
Investment analysis and future production and marketing demand forecast report of China's paper industry Ⓥ 2022 ~ 2028
Global and Chinese trisodium bicarbonate operation mode and future development forecast report Ⓢ 2022 ~ 2027
Review of last week's hot spots (6.27-7.3)
2022-2028 global gasket metal plate heat exchanger industry research and trend analysis report
Research Report on the development trend and Prospect of global and Chinese zinc antimonide market Ⓚ 2022 ~ 2027
2022-2028 research and trend analysis report on the global edible essence industry
The child container margin top acts on the parent container
Explanation of closures in golang
How do microservices aggregate API documents? This wave of show~
"How to connect the Internet" reading notes - FTTH
Go context 基本介绍
Write a jison parser from scratch (1/10):jison, not JSON