01Spring-01jdbc 未使用spring代码编写
时间:2021-06-16 18:10:14
收藏:0
阅读:0
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.zjw</groupId>
<artifactId>day01_eesy_01jdbc</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
</dependencies>
</project>
JdbcDemo1.java
package com.zjw;
import com.mysql.cj.jdbc.Driver;
import java.sql.*;
public class JdbcDemo1 {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
//注册驱动
// Driver driver = new Driver();
// DriverManager.registerDriver(driver);
Class.forName("com.mysql.cj.jdbc.Driver");
//获取连接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/eesy_jdbc?useSSL=false&serverTimezone=Asia/Shanghai", "root", "123456");
System.out.println(connection);
//获取操作数据库的预处理对象
PreparedStatement ps = connection.prepareCall("SELECT * FROM account");
//执行sql,得到结果集
ResultSet resultSet = ps.executeQuery();
//遍历结果集
while (resultSet.next()){
System.out.println(resultSet.getString("name"));
}
//释放资源
resultSet.close();
ps.close();
connection.close();
}
}
程序问题:
使用了具体的驱动类,如果不存在编译会报错(没导入mysql的jar包)。可以利用反射创建驱动类,解耦合Class.forName("具体类路径")
评论(0)