table of Contents
Introduction to related APIs in JDBC
DriverManager: drive management object
Connection: database connection object
PreparedStatement: execute SQL object
Extract tool classes and use configuration files to create connection pools
JDBC overview
JDBC: Java DataBase Connectivity. Its role is to operate databases through Java in foreign countries . In essence, it defines a set of rules (interfaces) for operating all relational databases, and then each database manufacturer implements this set of interfaces, providing The database drives the jar package, and then we use this interface (JDBC) to program to drive the implementation classes in the jar package
JDBC implementation steps
Before implementing JDBC, you first need to import the (mysql-connection-java-5.1.37-bin) jar package, and then start to execute the six-step operation of JDBC.
jar package link:
Link: https://pan.baidu.com/s/1LsyTxuoDGrOh2cqNt9UfaQ
Extraction code: nfn8
- Register driver
- Get database connection object, connection
- Define SQL
- Get the object that executes the SQL statement, statement
- Execute sql, receive the returned result
- process result
- Release resources
Case code:
public void testSave() throws Exception {
//1.注册驱动
DriverManager.registerDriver(new Driver());
String url = "jdbc:mysql://localhost:3306/student";
String username = "root";
String password = "root";
//2.获得连接
Connection connection = DriverManager.getConnection(url, username, password);
//3.获得语句执行者
Statement st = connection.createStatement();
//4.执行语句
String sql = "INSERT INTO tab_account VALUES(NULL , 'rose' , '1000')";
int count = st.executeUpdate(sql);
//5.处理结果
System.out.println(count);
//6.释放资源
st.close();
connection.close();
}
}
Introduction to related APIs in JDBC
DriverManager: drive management object
effect:
- Register driver
static void registerDriver(Driver driver):
Register with the given driver DriverManager
Write code using (dynamic loading class): Class.forName("com.mysql.jdbc.Driver").
By viewing the source code, it is found that there are static code blocks in the com.mysql.jdbc.Driver class
static{ try{ java.sql.DriverManager.registerDriver(new Driver); }catch(SQLException e){ throw new RuntimeException("Can't register driver!"); } }
The driver jar package after MySQL5 can omit the step of registering the driver
- Get database connection
方法:static Connection getConnection(String url,String user,String password)parameter:url : specify the path of the connectionSyntax: jdbc:mysql://ip address (domain name): port number/database nameDetails: If you are connecting to a local mysql server, and the default port of the mysql server is 3306, the url can be abbreviated: jdbc:mysql://database nameuser : database user namepassword : database password
Connection: database connection object
effect:
- Get executed SQL object
statement createStatement()
PreparedStatement prepareStatement(String sql)
- Management affairs
Open transaction: setAutoCommit(boolean autoCommit) calls this method to set the parameter to false, that is, open the transaction
Commit the transaction: commit()
Roll back the transaction: rollback()
Statement: execute SQL object
boolean execute(String sql): can execute any SQL
int executeUpdate(String sql): Execute the DML (addition, deletion, modification) statement, the return value is the number of rows affected, and judge whether the DML statement is executed successfully.
ResultSet executeQuery(String SQL): execute DQL (query) statement
ResultSet: result set object
boolean next(): The cursor moves down one line to determine whether the current end of the last line (whether there is data), if there is, it returns false, otherwise it returns true getXxxx (parameter): Get data
Xxx: represents the data type, such as getInt(int/String), getString(int/String) parameter
int represents the number of the column, starting from 1, String: represents the name of the column note
Steps for usage
Move the cursor down one line Determine whether there is data retrieve data
PreparedStatement: execute SQL object
{Prevent SQL injection, more efficient}
SQL injection problem: When splicing SQL, some SQL special keywords participate in the splicing of strings, which will cause security problems Solve the SQL injection problem, use PreparedStatemet object to solve Precompiled SQL: parameter use? as a placeholder step
Import the driver jar package, mysql-connector-java-5.1.37-bin.jar Register driver Get the database connection object Connection Define SQL
Note: SQL parameters use? As a placeholder, ---->select * from user where username=? and password=? Assign?
Method --->setXxx (parameter 1, parameter 2)
Parameter 1: The coding of the position starts from 1 Parameter 2: The value of? Execute SQL, receive returned results, no need to pass parameters process result Release resources
JDBC initial package case code:
Configuration file:
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///student
username=root
password=root
package com.james.Utils;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
private static String url;
private static String user;
private static String password;
private static String driver;
static{
//读取资源文件获取值
try {
//1 创建Properties集合类
Properties properties = new Properties();
//2 获取src路径下的文件的方式----->classLoader 类加载器
ClassLoader classLoader=JDBCUtils.class.getClassLoader();
URL res=classLoader.getResource("jdbc.properties");
// 获取配置文件路径
String path=res.getPath();
//3 加载文件
properties.load(new FileReader(path));
//4 获取数据
url=properties.getProperty("url");
user=properties.getProperty("user");
password=properties.getProperty("password");
//5 注册驱动
driver=properties.getProperty("driver");
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* 获取连接对象的方法
* */
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
Druid connection pool
The connection pool is a container for storing the database. When the system is initialized, the container is created. The container will apply for some connection objects. When the user accesses the database, the connection object will be obtained from the container. After the user accesses the database, the connection object will be returned to container.
advantage:
- Save resources and reduce server pressure
- Improve connection reusability and efficient user access
Hard coded way:
- Import the jar package link:
https://pan.baidu.com/s/1lHnZJ-uPbEVwOuodV8poHA
Extraction code: n04c
- Create object
- Configure the four basic parameters of database connection (driver, url, username, password)
- Set other parameters (maximum number of connections, minimum number of idle connections, maximum waiting time for obtaining connections)
- Get connection through connection pool object
- Use connection
- Call the connection, close() can return the connection
public class DRUIDDemo {
@Test
//硬编码,所有的配置都写到java代码中
public void test1() throws SQLException {
//1. 创建对象
DruidDataSource ds = new DruidDataSource();
//2. 设置数据库连接的4个基本参数(驱动,url,username,password)
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql:///student");
ds.setUsername("root");
ds.setPassword("1234");
//3. 设置其他的参数(最大连接的数量,最小连接空闲数量,获取连接最大等待时间)
ds.setMaxActive(10);
ds.setMinIdle(2);
ds.setMaxWait(2000);
//获取11个连接 ,会出现重复的连接
for (int i = 1; i <12 ; i++) {
//4. 通过连接池对象获取连接
Connection conn = ds.getConnection();
//5. 使用连接
System.out.println(conn);
if (i%7==0){
//6. 调用连接close()就可以归还连接
conn.close();
}
}
}
}
Extract tool classes and use configuration files to create connection pools
Tools:
package com.james.b_utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
/**
* 连接池的工具类
* 1.获得连接
* 2.释放资源(归还连接)
*/
public class DruidUtils {
//1.准备数据源
private static DataSource dataSource = null ;
//2.static静态代码块初始化连接池
static {
try {
//加载流
InputStream is = DruidUtils.class.getClassLoader().getResourceAsStream("db.properties");
//创建properties
Properties properties = new Properties();
//加载数据
properties.load(is);
//实例化连接池
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 从池中获得连接
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
}
xml configuration file (under the src folder):
#此处的properties 的key不能瞎写
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///student
username=root
password=root
initialSize=3
maxActive=10
maxWait=3000
package com.james.b_utils;
import java.sql.Connection;
import java.sql.SQLException;
public class TestDemo {
public static void main(String[] args) throws SQLException {
for(int i = 1 ; i <= 11 ; i++ ){
Connection connection = DruidUtils.getConnection();
System.out.println(i+"@@"+connection);
if(i==5){
//归还第五个连接
connection.close();//连接池对close方法都进行重写了
}
}
}
}