First import dependent
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.qublog</groupId>
<artifactId>spring01_jdbc</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
</dependencies>
</project>
JdbcDemo1.java
package com.qublog.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
//程序的耦合:程序间的依赖关系,包括:类之间的依赖、方法间的依赖。
//解耦:降低程序间的依赖关系,实际开发中应该做到编译期不依赖,运行时才依赖。
public class JdbcDemo1 {
public static void main(String[] args) throws Exception {
//注册驱动
DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver()) ;
//获取连接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/springtest?serverTimezone=UTC","root","1234");
//获取操作数据库的预处理对象
PreparedStatement pstm = connection.prepareStatement("select * from account");
//执行SQL,得到结果集
ResultSet resultSet = pstm.executeQuery();
//遍历结果集
while(resultSet.next()) {
System.out.println(resultSet.getString("name"));
}
//释放资源
resultSet.close();
pstm.close();
connection.close();
}
}
Run to get the result:
the pom.xml
<!--<dependencies>-->
<!--<dependency>-->
<!--<groupId>mysql</groupId>-->
<!--<artifactId>mysql-connector-java</artifactId>-->
<!--<version>8.0.16</version>-->
<!--</dependency>-->
<!--</dependencies>-->
Comment out, the result will be a compile-time error:
modify JdbcDemo1.java:
package com.qublog.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
//程序的耦合:程序间的依赖关系,包括:类之间的依赖、方法间的依赖。
//解耦:降低程序间的依赖关系,实际开发中应该做到编译期不依赖,运行时才依赖。
public class JdbcDemo1 {
public static void main(String[] args) throws Exception {
//注册驱动
//DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver()) ;
Class.forName("com.mysql.cj.jdbc.Driver");
//获取连接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/springtest?serverTimezone=UTC","root","1234");
//获取操作数据库的预处理对象
PreparedStatement pstm = connection.prepareStatement("select * from account");
//执行SQL,得到结果集
ResultSet resultSet = pstm.executeQuery();
//遍历结果集
while(resultSet.next()) {
System.out.println(resultSet.getString("name"));
}
//释放资源
resultSet.close();
pstm.close();
connection.close();
}
}
There will be run-time errors:
from the results can be analyzed, the first method has a strong dependence between classes. Our decoupling ideas:
- Use reflection to create objects, and avoid using the new keyword.
- Obtain the fully qualified class name of the object to be created by reading the configuration file.