Table of contents
1. Java database programming: JDBC
4. Summary of JDBC usage steps
5. JDBC common interfaces and classes
5.2 Database connection Connection
1. Java database programming: JDBC
JDBC, Java Database Connectivity, java database connection. It is a Java API for executing SQL statements. It is a database connection specification in Java. This API consists of some classes and interfaces in the java.sql.*, javax.sql.* packages. It provides a standard API for Java developers to operate databases and can provide unified access to multiple relational databases.
2. JDBCWorking Principle
- Java language access database operations are completely oriented to abstract interface programming
- Developing database applications does not need to be limited to the API of a specific database vendor.
- Program portability is greatly enhanced
3. JDBCUse
- Prepare the database driver package and add it to the project's dependencies:
Create the folder lib in the project and copy the dependency package mysql-connector-java-5.1.47.jar to lib. Then configure the jar package into the dependencies of this project: right-click the project Open Module Settings, in Modules, click the project, configure Dependencies, click +, JARS or Directories, configure the lib folder into the dependencies, indicating the folder The jar packages under are introduced as dependencies.
- Establish database connection
The URL parameter format of MySQL data connection is as follows:
jdbc:mysql://server address:port/database name?Parameter name=parameter value
// 加载JDBC驱动程序:反射,这样调用初始化com.mysql.jdbc.Driver类,即将该类加载到JVM方法
区,并执行该类的静态方法块、静态属性。
Class.forName("com.mysql.jdbc.Driver");
// 创建数据库连接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?
user=root&password=root&useUnicode=true&characterEncoding=UTF-8");
- Create an operation command (Statement)
//3.构造一个Sql
String sql =" insert into stu(id,name,age) values(1,zhang,3)";
//需要把 Sql语句转化为对象
PreparedStatement statement = connection.prepareStatement(sql);
- Use action commands to execute SQL
// 查询操作
preparedStatement.executeQuery();
// 新增、修改、删除操作
preparedStatement.executeUpdate();
- Process the result setResultSet.
//接受结果集合
ResultSet resultSet = statement.executeQuery();
//结果集遍历
while (resultSet.next()){
//移动光标
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
System.out.println(id+" "+name+" "+age+" ");
}
- Release resources
try {
if(resultSet != null){
resultSet.close();
}
if(preparedStatement != null){
preparedStatement.close();
}
if(connection != null){
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("数据库错误");
}
4. JDBC Summary of usage steps
1. Create a database connection Connection2. Create an operation command Statement3. Use operation commands to execute SQL4. Process the result set ResultSet5. Release resources
5. JDBCCommonly used Japanese class
5.1 JDBC API
5.2 ConnectionConnection
- One is to obtain it through the static method of DriverManager (driver management class):
// 加载JDBC驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 创建数据库连接
Connection connection = DriverManager.getConnection(url);
- One is to obtain it through the DataSource (data source) object. Will be used in actual applicationsDataSourceObject
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource)dataSource).setUrl("jdbc:mysql://localhost:3306/db1?serverTimezone=UTC");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("123456");
The difference between the above two methods is:
1. The Connection obtained by the DriverManager class cannot be reused. Every time the resource is released after use, the physical connection is closed through connection.close().
2. DataSource provides connection pool support. The connection pool will create a certain number of database connections during initialization. These connections can be reused. Every time the database connection is used and resources are released, calling connection.close() will recycle the Conncetion connection object.
5.3 StatementImage
There are two main ways to execute SQL:
- The executeQuery() method returns a single result set after execution, usually used in select statements.
- The return value of the executeUpdate() method is an integer indicating the number of affected rows, usually used for update, insert, and delete statements.
5.4 ResultSetResult
6. Sample code
import com.mysql.cj.jdbc.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class TestJDBC {
public static void main(String[] args) throws SQLException {
// MysqlDataSource dataSource = new MysqlDataSource();
//dataSource.setUrl();
//1. 创建数据源,即获取数据库的位置
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource) dataSource).setUrl("jdbc:mysql://localhost:3306/db1?serverTimezone=UTC");
((MysqlDataSource)dataSource).setUser("root");
((MysqlDataSource)dataSource).setPassword("123456");
// 2 .和数据库服务器建立连接
Connection connection = dataSource.getConnection();
//3.构造一个Sql
String sql =" insert into stu(id,name,age) values(?,?,?)";
// String sql =" insert into stu(id,name,age) values(1,zhang,3)";
//需要把 Sql语句转化为对象
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1,66);
statement.setString(2,"a");
statement.setInt(3,7);
//4.构造好的sql 发送给服务器;
int n = statement.executeUpdate();
System.out.println("n:"+ n);
//5.最后一步 释放资源
statement.close();
connection.close();
}
}
Conclusion:This ends the JDBC-related sharing. I hope it will be helpful to everyone’s study. If you have any questions or different opinions, please feel free to leave them in the comment area. Leave a message, ganxiezhich~~~