当前位置:网站首页>MySQL_ JDBC
MySQL_ JDBC
2022-07-03 13:13:00 【Tolerance speech】
1.JDBC
1. Concept
1. Database driven
drive : Sound card , The graphics card ……

Our program will deal with the database through database driver .
2.JDBC Concept
SUN In order to simplify the operation of developers on the database , Provides a java Specification of operating database , Be commonly called JDBC.
These specifications are made by specific manufacturers , For developers , We just need to master JDBC Interface can .

So we need to import a database driver package , Download address :https://dev.mysql.com/downloads/
2. First time to know JDBC Program
stay SQLyog in :
CREATE DATABASE jdbcStudy CHARACTER SET utf8 COLLATE utf8_general_ci;
USE jdbcStudy;
CREATE TABLE users(
id INT PRIMARY KEY,
`name` VARCHAR(50),
`password` VARCHAR(30),
`email` VARCHAR(60),
birthday DATE
);
INSERT INTO users(`id`,`name`,`password`,`email`,`birthday`) VALUES(1,' Zhang San ','123456','[email protected]','1990-12-4'),(2,' Li Si ','1234567','[email protected]','2000-08-2'),(3,' Zhao Wu ','3456789','[email protected]','2003-07-11');
stay idea in :
Create a project
Import database driver
- Create a new one lib Catalog , And then put jar The bag dragged in
- Right click add as library Add as library
Write code
import java.sql.*; public class jdbcFirstDemo { public static void main(String[] args) throws ClassNotFoundException, SQLException { //1. The load driver Class.forName("com.mysql.jdbc.Driver");// Fixed writing , The load driver //2. User information and url //useUnicode=true Support Chinese coding ,chaeacterEncoding=utf8 Avoid random code ,useSSL=true Using secure connections String url ="jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&chaeacterEncoding=utf8&useSSL=true"; String username = "root"; String password = "1234"; //3. Successful connection , Database objects connection On behalf of the database Connection connection = DriverManager.getConnection(url,username,password); //4. perform SQL The object of Statement Statement statement = connection.createStatement(); //5. perform SQL To execute SQL, View return results String sql= "SELECT * FROM `users`"; ResultSet resultSet = statement.executeQuery(sql);// perform sql, The result set returned , The result set encapsulates all the query results while(resultSet.next()){ System.out.println("id="+resultSet.getObject("id")); System.out.println(" name ="+resultSet.getObject("name")); System.out.println(" password ="+resultSet.getObject("password")); System.out.println(" mailbox ="+resultSet.getObject("email")); System.out.println(" Birthday ="+resultSet.getObject("birthday")); System.out.println("===================="); } //6. Release the connection resultSet.close(); statement.close(); connection.close(); } }result :

url
String url ="jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&chaeacterEncoding=utf8&useSSL=true";
//mysql---3306
//jdbc:mysql:// The host address : Port number 、 Database name ? Parameters 1& Parameters 2& Parameters 3
//oralce---1521
//jdbc:oralce:thin:@localhost:1521:sid
connection
//connection Database objects
connection.rollback();
connection.commit();
connection.setAutoCommit();
statement
//statement perform sql The object of
PreparedStatement preparedStatement = connection.prepareStatement();// This is safer
Statement statement = connection.createStatement();
statement.executeQuery();// Query operation , Return result set resultSet
statement.execute();// Carry out any sql
statement.executeLargeUpdate();// to update , Insert , Delete all with this , Returns the number of rows affected
resultSet
// Return result set
//1. Gets the specified data type
resultSet.getObject()// Use when you don't know the column type
resultSet.getInt();
resultSet.getFloat();
resultSet.getDouble();
resultSet.getBoolean();
resultSet.getDate();
//2. Traverse , The pointer
resultSet.next();// Move to the next data
resultSet.beforeFirst();// Move to the front
resultSet.afterLast();// Move to the back
resultSet.previous();// Move to previous line
resultSet.absolute(row);// Move to specified row
Release resources , What has to be done
resultSet.close();
statement.close();
connection.close();// special connection
3.statement object
JDBC Inside statement Object to send... To the database SQL sentence , Want to complete the addition, deletion, modification and query of the database , You only need to send the add, delete, change and query statement to the database through this object .
statement Object's executeUpdate Method , Used to send additions, deletions, and modifications to the specified database sql sentence ,executeUpdate After execution , Will return an integer , That is, several rows of data in the database have changed .
CRUD operation -create
Statement st = conn.ceateStatement();
String sql = "insert into user(...) values(...,...)";
int num = st.executeUpdate(sql);
if(num>0){
System.out.println(" Insert the success !");
}
CRUD operation -delete
Statement st = conn.ceateStatement();
String sql = "delete from user where id=1";
int num = st.executeUpdate(sql);
if(num>0){
System.out.println(" Delete successful !");
}
CRUD operation -update
Statement st = conn.ceateStatement();
String sql = "update user set name ='' where name= ''";
int num = st.executeUpdate(sql);
if(num>0){
System.out.println(" Modification successful !");
}
4. Extract tool class

driver = com.mysql.jdbc.Driver
url =jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&chaeacterEncoding=utf8&useSSL=true
username = root
password = 1234
package utils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class jdbcUtils {
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;
static {
try{
// Access to resources
InputStream in = jdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(in);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
//1. The driver can be loaded only once
Class.forName(driver);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
// Get the connection
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,username,password);
}
// Release the connection
public static void release(Connection conn, Statement st, ResultSet rs){
if (rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (st != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
import utils.jdbcUtils;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class testInsert {
public static void main(String[] args) {
Connection conn = null;
Statement st = null;
try {
conn = jdbcUtils.getConnection();// Get database connection
st = conn.createStatement();// perform sql The object of
String sql= "INSERT INTO users(`id`,`name`,`password`,`email`,`birthday`) "+"VALUES(6,' cheng ','453','[email protected]','1998-3-1')";
int i = st.executeUpdate(sql);
if (i>0){
System.out.println(" success !");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
jdbcUtils.release(conn,st,null);
}
}
}
5.sql Injection problem
sql Vulnerability , It can lead to The data reveal that . Nature is :sql Will be stitched together (or).
import utils.jdbcUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class sqlInjection {
public static void main(String[] args) {
//login(" Zhang San ","123456"); Normal query ----- name : Zhang San password :123456
login(" 'or' 1=1 "," 'or' 1=1");// All user names and passwords have been found
}
// Log in to business
public static void login(String username ,String password){
Connection conn = null;
Statement st = null;
try {
conn = jdbcUtils.getConnection();// Get database connection
st = conn.createStatement();// perform sql The object of
//SELECT * FROM `users` WHERE `name`=' Zhang San ' AND `password`=123456;
String sql= "SELECT * FROM `users` WHERE `name`='"+username+"' AND `password`='"+password+"'";
ResultSet resultSet = st.executeQuery(sql);// perform sql, The result set returned , The result set encapsulates all the query results
while(resultSet.next()) {
System.out.println(" name :" + resultSet.getObject("name"));
System.out.println(" password :" + resultSet.getObject("password"));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
jdbcUtils.release(conn,st,null);
}
}
}
6.PreparedStatement object
It can prevent sql Injection problem , And more efficient .
import utils.jdbcUtils;
import java.sql.Connection;
import java.util.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class psInsert {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement st = null;
try {
conn = jdbcUtils.getConnection();
// difference
// Use ? Placeholders replace specific parameters
String sql = "INSERT INTO users(`id`,`name`,`password`,`email`,`birthday`) "+"VALUES(?,?,?,?,?)";
st = conn.prepareStatement(sql);// precompile sql, First write sql, But it doesn't execute
// Assign parameters manually
st.setInt(1,8);
st.setString(2,"q");
st.setString(3,"2345");
st.setString(4,"[email protected]");
// Be careful :java.util.Date yes java Of
// java.sql.Date It's database
st.setDate(5,new java.sql.Date(new Date().getTime()));
// perform
int i = st.executeUpdate();
if (i>0){
System.out.println(" Insert the success !");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
jdbcUtils.release(conn,st,null);
}
}
}
7. Use idea Connect to database

1. Pay attention when connecting : To put Drive import go in , And there's more Time zone problem You need to add it manually in the advanced settings


2. Add the desired database

3. After importing the database , Double click to view the table

4. Then you can modify the data directly , And submit
5. Enter writing sql Where to code

6. Write code

8. Business
Either they all succeed , Or they all failed .
import utils.jdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class transaction {
public static void main(String[] args) throws SQLException {
Connection conn = null;
PreparedStatement st = null;
try {
conn = jdbcUtils.getConnection();
// Turn off automatic submission of the database , Automatically opens the transaction
conn.setAutoCommit(false);// Open transaction
String sql1 = "update account set money = money - 100 where name = 'A' ";
st = conn.prepareStatement(sql1);
st.executeUpdate();
String sql2 = "update account set money = money + 100 where name = 'B' ";
st = conn.prepareStatement(sql2);
st.executeUpdate();
// Business finished , Commit transaction
conn.commit();
System.out.println(" Submit successfully ");
} catch (SQLException throwables) {
conn.rollback();// If it fails, roll back , Don't write this sentence , Failure will also be rolled back automatically by default
throwables.printStackTrace();
}finally {
jdbcUtils.release(conn,st,null);
}
}
}
result :
9. Database connection pool
We are now database connection ---- perform ---- Release , But the whole process of connection release is a waste of resources . So we need to write a connection pool , To write a connection pool, you only need to implement An interface Datasource( The interface will not change , The method won't change ). After using these data connection pools , When we develop projects , There is no need to write the code to connect to the database !
Pool technology : Prepare some Advance resources , Come here, even ready :
Open door — salesman : wait for ----- service ---- close
How many salesmen do you need here ? This leads to Minimum connections , This can be set according to your common connection number
maximum connection : The maximum carrying capacity of the service , If the maximum number of connections is reached , The rest needs to wait in line
Waiting for timeout : If the waiting time is too long , Just tell the person behind to leave
Some common open source database connection pools :
DBCP
C3P0
Druid: alibaba.com
1. DBCP
Import jar package , Import and add as library :
Commons-dbcp.jar: Implementation of connection pool
Commons-pool.jar: Dependency library for connection pool implementation
Download address :http://commons.apache.org/proper/commons-dbcp/download_dbcp.cgi,http://commons.apache.org/proper/commons-pool/download_pool.cgi
# Database driven , connections setting up : The name here is DBCP The data source is defined
driverClassName=com.mysql.jdbc.Driver
# Database connection address
url=jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&chaeacterEncoding=utf8&useSSL=true
# user name
username=root
# password
password=1234
# Initialize connection
initialSize=10
# Maximum number of database connections to the connection pool . Set to 0 Means unlimited
maxActive=50
# Maximum free connection , Maximum idle time for database connection . More than free time , The database connection will be marked as unavailable , And then it's released . Set to 0 Means unlimited
maxIdle=20
# Minimum free connection
minIdle=5
# Maximum connection setup wait time , Milliseconds . If this time is exceeded, an exception will be received . Set to -1 Means unlimited
maxWait=60000
# Configure monitoring statistics interception filters
#filters=stat
#JDBC The format of the connection attribute attribute attached to the driver when establishing the connection must be as follows :[ Property name =property;]
# Be careful :"user" And "password" Two attributes are explicitly passed , So there's no need to include them
connectionProperties=useUnicode=true;characterEncoding=UTF8
# Specifies the automatic commit of connections created by the connection pool (auto-commit) state
defaultAutoCommit=true
#driver default Specify the transaction level of the connection created by the connection pool (TransactionIsolation).
# The available values are one of the following :( details javadoc.)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_UNCOMMITTED
package utils;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class dbcpUtils {
private static DataSource dataSource = null;
static {
try{
// Access to resources
InputStream in = dbcpUtils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
Properties properties = new Properties();
properties.load(in);
// create data source Factory mode -- Create objects
dataSource = BasicDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
// Get the connection
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
// Release the connection
public static void release(Connection conn, Statement st, ResultSet rs){
if (rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (st != null){
try {
st.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
test DBCP The code is the same as before , Just change one sentence :conn = dbcpUtils.getConnection().
2.C3P0
Import jar package , Import and add as library :
- c3p0-0.9.5.2.jar
- mchange-commons-java-0.2.15.jar
<?xml version="1.0" encoding="UTF-8"?>
<!--xml No need to read , Automatically match when loading -->
<c3p0-config>
<!-- The default configuration , If not specified, use this configuration -->
<default-config>
<property name="user">root</property>
<property name="password">1234</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&chaeacterEncoding=utf8&useSSL=true</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="checkoutTimeout">30000</property>
<property name="idleConnectionTestPeriod">30</property>
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">2</property>
<property name="maxStatements">200</property>
</default-config>
<!-- Named configuration , It can be implemented through method calls -->
<named-config name="MySQL">
<property name="user">root</property>
<property name="password">1234</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcStudy?useUnicode=true&chaeacterEncoding=utf8&useSSL=true</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<!-- How many connections in the pool increase at a time if there are not enough connections -->
<property name="acquireIncrement">5</property>
<!-- Number of connections when initializing the database connection pool -->
<property name="initialPoolSize">20</property>
<!-- The maximum number of database connections in the database connection pool -->
<property name="maxPoolSize">25</property>
<!-- The minimum number of database connections in the database connection pool -->
<property name="minPoolSize">5</property>
</named-config>
</c3p0-config>
package utils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class c3p0Utils {
private static ComboPooledDataSource dataSource = null;
static {
try{
dataSource = new ComboPooledDataSource("MySQL");
} catch (Exception e) {
e.printStackTrace();
}
}
// Get the connection
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
// Release the connection
public static void release(Connection conn, Statement st, ResultSet rs){
if (rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (st != null){
try {
st.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
test DBCP The code is the same as before , Just change one sentence :conn = c3p0Utils.getConnection().
边栏推荐
- Flink SQL knows why (12): is it difficult to join streams? (top)
- C graphical tutorial (Fourth Edition)_ Chapter 13 entrustment: what is entrustment? P238
- Tencent cloud tdsql database delivery and operation and maintenance Junior Engineer - some questions of Tencent cloud cloudlite certification (TCA) examination
- Sword finger offer 14- ii Cut rope II
- STM32 and motor development (from MCU to architecture design)
- Kotlin notes - popular knowledge points asterisk (*)
- Idea full text search shortcut ctr+shift+f failure problem
- How to get user location in wechat applet?
- Method overloading and rewriting
- 【数据挖掘复习题】
猜你喜欢

Flink SQL knows why (12): is it difficult to join streams? (top)

Sitescms v3.1.0 release, launch wechat applet

【数据库原理及应用教程(第4版|微课版)陈志泊】【第四章习题】

Analysis of the influence of voltage loop on PFC system performance

2022-02-14 analysis of the startup and request processing process of the incluxdb cluster Coordinator

【数据库原理及应用教程(第4版|微课版)陈志泊】【第六章习题】

Flink code is written like this. It's strange that the window can be triggered (bad programming habits)

【Colab】【使用外部数据的7种方法】

Huffman coding experiment report

Brief introduction to mvcc
随机推荐
有限状态机FSM
stm32和电机开发(从mcu到架构设计)
The upward and downward transformation of polymorphism
剑指 Offer 14- I. 剪绳子
【R】 [density clustering, hierarchical clustering, expectation maximization clustering]
2022-01-27 redis cluster brain crack problem analysis
php:&nbsp; The document cannot be displayed in Chinese
高效能人士的七个习惯
显卡缺货终于到头了:4000多块可得3070Ti,比原价便宜2000块拿下3090Ti
[network counting] Chapter 3 data link layer (2) flow control and reliable transmission, stop waiting protocol, backward n frame protocol (GBN), selective retransmission protocol (SR)
Sitescms v3.0.2 release, upgrade jfinal and other dependencies
【习题六】【数据库原理】
双链笔记 RemNote 综合评测:快速输入、PDF 阅读、间隔重复/记忆
Flink SQL knows why (XIV): the way to optimize the performance of dimension table join (Part 1) with source code
[data mining review questions]
[combinatorics] permutation and combination (the combination number of multiple sets | the repetition of all elements is greater than the combination number | the derivation of the combination number
2022-01-27 use liquibase to manage MySQL execution version
Flink code is written like this. It's strange that the window can be triggered (bad programming habits)
Image component in ETS development mode of openharmony application development
Huffman coding experiment report