package org.example.jdbc;
import java.sql.*;
public class FirstExample {
// 数据库信息
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
// 用户名、密码
static final String USER = "root";
static final String PASS = "jianan";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 加载数据库驱动
Class.forName(JDBC_DRIVER);
// 连接数据库
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// 执行sql
stmt = conn.createStatement();
String sql = "SELECT id, age, first, last FROM Employees";
rs = stmt.executeQuery(sql);
// 遍历结果集
while (rs.next()) {
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
System.out.printf("%d,%d,%s,%s", id, age, first, last);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放数据库相关资源
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
/*
1,28,贾,楠
2,29,孙,晨曦
*/