当前位置:网站首页>JDBC MySQL 01 JDBC operation MySQL (add, delete, modify and query)
JDBC MySQL 01 JDBC operation MySQL (add, delete, modify and query)
2022-07-27 18:54:00 【A sea of clouds, a first thought】
Chapter vii. JDBC
List of articles
- Chapter vii. JDBC
- One 、 Learning goals
- Two 、 What is? JDBC?
- 3、 ... and 、 Why JDBC?
- Four 、JDBC Architecture
- 5、 ... and 、JDBC Programming steps
- 6、 ... and 、JDBC API
- 7、 ... and 、JDBC Working process diagram :
- 8、 ... and 、JDBC Programming templates
- Nine 、 Three elements of database connection
- Ten 、 Use pure Java Way to connect MySql database :
- 11、 ... and 、 Use Statement Execute the object to realize the new operation
- Twelve 、 Use Statement Execute object implementation modification
- 13、 ... and 、 Use Statement and ResultSet Implement query operation
- fourteen 、Statement Common methods
- 15、 ... and 、ResultSet Common methods
- sixteen 、SQL Inject
- seventeen 、 How to avoid SQL Injection potential ?
- eighteen 、PreparedStatement Perform object
- nineteen 、 Common mistakes
- twenty 、 Summary of this chapter
One 、 Learning goals
- understand JDBC principle
- master Connection Use of interfaces
- master Statement Use of interfaces
- master ResultSet Use of interfaces
- master PreparedStatement Use of interfaces
Two 、 What is? JDBC?
JDBC(Java DataBase Connectivity) yes Java Short for database connection technology . yes Java And the database bridge , It mainly provides the ability to connect various commonly used databases .
3、 ... and 、 Why JDBC?
Data needs to be persisted , It must be saved on disk , Not in memory . For the data in the program , We all use database management system to manage , Nothing more than adding, deleting, modifying and checking , that If in Java Database operation in the program ? This requires the use of JDBC 了 . in fact , stay Java There are several techniques for operating databases in , For example, the most The original JDBC The way , be based on JDBC Packaged MyBatis frame , Or is it ORM frame Hibernate、SpirngDataJPA etc. .
So-called JDBC In fact, it is a typical case of interface oriented programming ,SUN The company is only responsible for defining JDBC API Interface ( That is to say interface class ), But I'm not responsible for writing specific implementation classes , The preparation of specific implementation classes is handed over to various database manufacturers to implement . The advantage of this is , Once the underlying database is replaced ,Java There is no need to change the program in the code . This group operates the database API be located Java The class library java.sql and javax.sql Two bags
Four 、JDBC Architecture
5、 ... and 、JDBC Programming steps
- stay Java Through the program JDBC The steps to operate the database are fixed , as follows :
- Load and register the driver Class.forName(“com.mysql.cj.jdbc.Driver”)
- establish Connection Connection object ( namely Java The program is established between the client and the database server socket Connect , More specifically tcp Connect )
- establish Statement object
- perform SQL sentence
- obtain ResultSet object ( If it is not a query operation , There will be no such step )
- Release resources ( The network connection is always released , Otherwise, as the number of connections increases , The database server may crash when it is serious )
6、 ... and 、JDBC API
Provider : Sun company
The main function : Establish a connection to the database 、 perform SQL sentence 、 Processing results
Content : Interfaces and classes for programmers to call , Integrated into the java.sql and javax.sql In bag Such as :
1、DriverManager class Driver management
2、Connection Interface Connection object
3、Statement Interface Perform object
4、ResultSet Interface Result set
6.1DriverManager
- Provider :Sun company
- effect : Manage a variety of JDBC drive
6.2JDBC drive
- Provider : Database vendors
- effect : Responsible for connecting various databases
6.3JDBC API The main function :
Establish a connection to the database 、 perform SQL sentence 、 Processing results
DriverManager : Depending on the database , management JDBC drive
Connection : Responsible for connecting to the database and the task of transferring data
Statement : from Connection produce 、 Responsible for the execution of SQL sentence
ResultSet: Be responsible for the preservation of Statement The query result after execution
6.4Driver Interface
Driver The interface is provided by the database manufacturer , As java Developer , Just use Driver The interface will do . In programming, you should connect to the database , You must first load a specific vendor's database driver , Different databases have different loading methods . Such as :
load MySql drive :Class.forName(“com.mysql.jdbc.Driver”);
load Oracle drive :Class.forName(“oracle.jdbc.driver.OracleDriver”);
6.5Connection Interface
Connection A connection to a specific database ( conversation ), Execute in the connection context sql Statement and return the result .
DriverManager.getConnection(url, user, password)The method is based on JDBC URL Database defined in Connection Connected to the .// Connect MySql database : Connection conn = DriverManager.getConnection("jdbc:mysql://host:port/database", "user", "password"); // Connect Oracle database : Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@host:port:database", "user", "password"); // Connect SqlServer database : Connection conn = DriverManager.getConnection("jdbc:microsoft:sqlserver://host:port; DatabaseName=database", "user", "password");
7、 ... and 、JDBC Working process diagram :
8、 ... and 、JDBC Programming templates
Nine 、 Three elements of database connection
java.sql.Driver Implementation class of interface (JDBC API The connection with the corresponding database server depends on this interface , Otherwise, how to establish a relationship between the interface and the implementation class ?)
- This driver implementation class is in the drivers provided by various database manufacturers
Connect URL( This url The network address and port number of the database server are specified in , And want to use DBMS Which database in )
- This URL In fact, it is equivalent to a hyperlink , A website , But the protocol it uses is jdbc It's just an agreement . As shown in the figure below, the driver will be based on this URL The rules of , Take out URL Useful information in
- User name and password ( To operate a database , You must provide the corresponding user name and password to verify your identity )
- This is in JDBC API Can be specified separately in , You can also splice it directly to url In the parameters after
Ten 、 Use pure Java Way to connect MySql database :
from JDBC Drive direct access to the database
advantage : Completely Java Code , Fast 、 Cross platform
shortcoming : Access to different databases requires downloading dedicated JDBC drive
package cn.ketai.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * @author Aiden */ public class JDBCDemo { /** * preparation : * 1. Download from official website MySql Drive pack :https://dev.mysql.com/downloads/file/?id=494900 * 2. Introduce the drive package into the project */ public static void main(String[] args) { Connection conn = null;// Connection object try { // 1. The load driver Class.forName("com.mysql.cj.jdbc.Driver"); // 2. Establish a database connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/epet?serverTimezone=Asia/Shanghai", "root", "root"); // Determine if the connection is successful if (conn != null) { System.out.println(" Successful connection ."); } else { System.out.println(" The connection fails !!!"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if (conn != null) { // 3. If the connection is not empty, close the current connection try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }
11、 ... and 、 Use Statement Execute the object to realize the new operation
package cn.ketai.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; /** * @author Aiden */ public class StatementDemo { public static void main(String[] args) { Connection conn = null;// Connection object Statement stmt = null;// Perform object try { // 1. The load driver Class.forName("com.mysql.cj.jdbc.Driver"); // 2. Establish a database connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/epet?serverTimezone=Asia/Shanghai", "root", "root"); // 3. Instantiate the execution object stmt = conn.createStatement(); // 4. Prepare the new to be executed Sql sentence : String sql = "INSERT INTO `dog`(`name`,`health`,`love`,`strain`)VALUES (' A mu ',98,90,' Shepherd Dog ');"; // 5. Start execution and return the execution result , Return the number of affected rows int result = stmt.executeUpdate(sql); if (result > 0) { System.out.println(" Successful operation "); } else { System.out.println(" operation failed !!!"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if (stmt != null) { try { stmt.close();// Close the execution object } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close();// Close the current connection } catch (SQLException e) { e.printStackTrace(); } } } } }
Twelve 、 Use Statement Execute object implementation modification
package cn.ketai.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; /** * @author Aiden */ public class StatementDemo2 { public static void main(String[] args) { Connection conn = null;// Connection object Statement stmt = null;// Perform object try { // 1. The load driver Class.forName("com.mysql.cj.jdbc.Driver"); // 2. Establish a database connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/epet?serverTimezone=Asia/Shanghai", "root", "root"); // 3. Instantiate the execution object stmt = conn.createStatement(); // 4. Prepare the modifications to be performed Sql sentence : String sql = "update dog set love=90,health=100 where id=1;";// Change implemented sql sentence // 5. Start execution and return the execution result , Return the number of affected rows int result = stmt.executeUpdate(sql); if (result > 0) { System.out.println(" Successful operation "); } else { System.out.println(" operation failed !!!"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if (stmt != null) { try { stmt.close();// Close the execution object } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close();// Close the current connection } catch (SQLException e) { e.printStackTrace(); } } } } }
13、 ... and 、 Use Statement and ResultSet Implement query operation
package cn.ketai.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * @author Aiden */ public class ResultSetDemo { public static void main(String[] args) { Connection conn = null;// Connection object Statement stmt = null;// Perform object ResultSet rs=null;// Result set try { // 1. The load driver Class.forName("com.mysql.cj.jdbc.Driver"); // 2. Establish a database connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/epet?serverTimezone=Asia/Shanghai", "root", "root"); // 3. Instantiate the execution object stmt = conn.createStatement(); // 4. Prepare the query to be executed Sql sentence : String sql = "SELECT `id`,`name`,`health`,`love`,`strain` FROM `dog`;"; //5. Start execution and return the execution result rs=stmt.executeQuery(sql) ; // Loop traversal display System.out.println(" Number \t name \t Health value \t Intimacy \t Varieties "); while (rs.next()) { System.out.println(rs.getInt("id")+"\t"+rs.getString("name")+"\t" +rs.getInt("health")+"\t"+rs.getInt("love")+"\t"+rs.getString("strain")); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if(rs!=null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (stmt != null) { try { stmt.close();// Close the execution object } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close();// Close the current connection } catch (SQLException e) { e.printStackTrace(); } } } } }
fourteen 、Statement Common methods
Method name say bright ResultSet executeQuery(String sql) perform SQL Query and get ResultSet object int executeUpdate(String sql) Insert can be performed 、 Delete 、 Update and other operations , The return value is the number of rows affected by the operation ** boolean execute(String sql) Can execute any SQL sentence , Then get a Boolean value , Indicates whether to return ResultSet
15、 ... and 、ResultSet Common methods
Method name say bright boolean next( ) Moves the cursor down one line from its current position boolean previous() The cursor moves up one line from its current position void close() close ResultSet object int getInt(int colIndex) With int Get the specified column number value of the current row of the result set in the form of int getInt(String colLabel) With int Get the specified column name value of the current row of the result set in the form of float getFloat(int colIndex) With float Get the specified column number value of the current row of the result set in the form of float getFloat(String colLabel) With float Get the specified column name value of the current row of the result set in the form of String getString(int colIndex) With String Get the specified column number value of the current row of the result set in the form of String getString(String colLabel) With String Get the specified column name value of the current row of the result set in the form of
sixteen 、SQL Inject
package cn.ketai.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; /** * @author Aiden */ public class LoginDemo { public static void main(String[] args) { Connection conn = null;// Connection object Statement stmt = null;// Perform object ResultSet rs = null;// Result set Scanner input = new Scanner(System.in); try { // 1. The load driver Class.forName("com.mysql.cj.jdbc.Driver"); // 2. Establish a database connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/epet?serverTimezone=Asia/Shanghai", "root", "root"); // 3. Instantiate the execution object stmt = conn.createStatement(); System.out.println(" Please enter a user name :"); String name = input.next(); System.out.println(" Please input a password :"); String password = input.next(); // 4. Splice login query statements : String sql = " SELECT * FROM `master` WHERE `name`='" + name + "' AND `password`='" + password + "';"; // 5. Start execution and return the execution result rs = stmt.executeQuery(sql); if (rs.next()) { System.out.println(" Login successful ."); }else { System.out.println(" Login failed , Wrong username and password !"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (stmt != null) { try { stmt.close();// Close the execution object } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close();// Close the current connection } catch (SQLException e) { e.printStackTrace(); } } } } }test result :
Please enter a user name : Li Ming Please input a password : 123'or'1'='1 Login successful .
seventeen 、 How to avoid SQL Injection potential ?
Use PreparedStatement Interface
- Inherited from Statement Interface
- Than Statement Objects are more flexible to use , More efficient
- Improved code maintainability , Improved security .
eighteen 、PreparedStatement Perform object
package cn.ketai.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; /** * @author Aiden */ public class PreparedStatementDemo { public static void main(String[] args) { Connection conn = null;// Connection object PreparedStatement pstmt = null;// Perform object ResultSet rs = null;// Result set Scanner input = new Scanner(System.in); try { // 1. The load driver Class.forName("com.mysql.cj.jdbc.Driver"); // 2. Establish a database connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/epet?serverTimezone=Asia/Shanghai", "root", "root"); // User control day input System.out.println(" Please enter a user name :"); String name = input.next(); System.out.println(" Please input a password :"); String password = input.next(); // 3. Login validation query statement : String sql = " SELECT * FROM `master` WHERE `name`=? AND `password`=?;"; // 4. Instantiate the execution object pstmt = conn.prepareStatement(sql); //5. Set parameters pstmt.setObject(1, name); pstmt.setObject(2, password); // 5. Start execution and return the execution result rs = pstmt.executeQuery(); if (rs.next()) { System.out.println(" Login successful ."); } else { System.out.println(" Login failed , Wrong username and password !"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (pstmt != null) { try { pstmt.close();// Close the execution object } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close();// Close the current connection } catch (SQLException e) { e.printStackTrace(); } } } } }
nineteen 、 Common mistakes
Use JDBC When connecting to the database , Frequent mistakes
- JDBC The name of the driver class is written incorrectly , Lead to ClassNotFoundException abnormal
- Data connection string 、 Database user name 、 Wrong password , Lead to SQLException abnormal
- After the database operation , The database connection is not closed , As a result, system resources are still occupied
- The close database connection statement is not put into finally In the block , As a result, the statement may not be executed
twenty 、 Summary of this chapter
边栏推荐
- 音乐律动七彩渐变灯芯片--DLT8S04A-杰力科创
- How to send external mail to the company mailbox server on the Intranet
- Generate PDM file from Navicat export table
- Full automatic breast pump chip dltap703sd
- LeetCode 刷题 第二天
- Filebeat.yml configuration file about the configuration of multiple services
- Knowledge map - Jieba, pyhanlp, smoothnlp tools to realize Chinese word segmentation (part of speech)
- Valueerror: found input variables with inconsistent numbers of samples: [80019456, 26673152] [error reporting]
- Uploading and downloading of files
- Uni app label jump
猜你喜欢

商品推荐和分类商品推荐

LeetCode 刷题 第一天

Login page tablelayout

Uniapp H5 cross domain problem

Using Jieba and pyhanlp tools to extract keyword words and sentences

MySQL 03 高级查询(一)

Basic operations of MySQL view

Mini washing machine touch chip dlt8ma12ts Jericho

Uni app traversal array rendering data vertical rendering

Idea 2020.1 Community Edition download experience
随机推荐
Overview of Baidu map technology, and application development of basic API and webapi
Personal Center - order business process
网红RGB镜子灯触摸芯片-DLT8S15B-杰力科创
瑞吉外卖sql表
js中的函数与DOM获取元素和事件属性的使用
Quick access to website media resources
C basic concepts list description suggestions collection
Wechat payment and payment callback
【npm】 无法将“npm”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。
MySQL 主从复制数据不一致,怎么办?
文件的上传和下载
Electric heating neck pillow chip-dltap703sc
Build a simple knowledge question and answer system
Run the uniapp to the mobile phone (real machine debugging)
阿里p8总结的10条 SQL 优化方案(非常实用)
MySQL create event execution task
飞机大战英雄出场加子弹实现
Machine learning -- error caused by only one kind of label data in SVM training set
Mini washing machine touch chip dlt8ma12ts Jericho
ridis命令笔记





