首先,创建chapter01数据库并创建users表插入数据。
users表数据如下:
其次,新建Java类,该类用于读取数据库中的表,并将结果输出。
操作如下:
- 1.注册数据库的驱动。
Class.forName("com.mysql.cj.jdbc.Driver");
注意:此时代码会报错,需用try catch包围。
- 2.通过DriverManager获取数据库连接
String url = "jdbc:mysql://localhost:3306/chapter01?useSSL=false&serverTimezone=UTC";
String username = "root";
String password = "123456";
Connection conn = DriverManager.getConnection(url, username, password);
- 3.通过Connection对象获取Statement对象
Statement stmt = conn.createStatement();
- 4.使用Statement执行SQL语句
String sql = "select * from users";
ResultSet rs = stmt.executeQuery(sql);
- 5.操作ResultSet结果集
System.out.println("id|name|password|email|birthday");
while (rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String psw = rs.getString("password");
String email = rs.getString("email");
Date birthday = rs.getDate("birthday");
System.out.println(id+"|"+name+"|"+psw+"|"+email+"|"+birthday);
}
- 6.回收数据库资源
if (rs!=null){
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
rs=null;
}
if(stmt!=null){
try {
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
stmt=null;
}
if(conn!=null){
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
conn=null;
}
注意:回收数据库资源需在finally下进行
- 7.运行结果为:
完整代码如下:
package cn.itcast.jdbc.example;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Example01 {
public static void main(String[] args) throws SQLException {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//1.注册数据库的驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.通过DriverManager获取数据库连接
String url = "jdbc:mysql://localhost:3306/chapter01?useSSL=false&serverTimezone=UTC";
String username = "root";
String password = "123456";
conn = DriverManager.getConnection(url, username, password);
//3.通过Connection对象获取Statement对象
stmt = conn.createStatement();
//4.使用Statement执行SQL语句
String sql = "select * from users";
rs = stmt.executeQuery(sql);
//5.操作ResultSet结果集
System.out.println("id|name|password|email|birthday");
while (rs.next()){
int id = rs.getInt("id");
String name = rs.getString("name");
String psw = rs.getString("password");
String email = rs.getString("email");
Date birthday = rs.getDate("birthday");
System.out.println(id+"|"+name+"|"+psw+"|"+email+"|"+birthday);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
//6.回收数据库资源
if (rs!=null){
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
rs=null;
}
if(stmt!=null){
try {
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
stmt=null;
}
if(conn!=null){
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
conn=null;
}
}
}
}