package jdbc;
import java.sql.*;
public class Demo {
public static void main(String[] args) throws ClassNotFoundException {
// 1. 加载驱动,使用反射知识
Class.forName("com.mysql.cj.jdbc.Driver");
try (
// 2. 使用 DriverManager 获取数据库连接
// 其中返回的 Connection 就代表了 Java 程序和数据库的连接
// 不同数据库的 URL 写法需要查询驱动文档,用户名、密码由 DBA 分配
Connection conn = DriverManager.getConnection(
"jdbc:mysql://127.0.0.1:3306/cade?useSSL=false"
, "root", "root");
// 3. 使用 Connection 对象来创建一个 Statement 对象
Statement stmt = conn.createStatement();
// 4. 执行 SQL 语句
ResultSet rs = stmt.executeQuery("select * from emp")
) {
// ResultSet 有一系列的 getXxx(列索引 | 列名)方法,
// 用于获取记录指针指向行、特定列的值,不断地使用 next() 将记录指针下移一行
// 如果移动之后记录指针依然指向有效行,则 next()方法返回 true
// 注意:getXxx方法的参数“列索引”是从1开始的
while (rs.next()) {
System.out.println(rs.getInt(1) + "t" +
rs.getString(2) + "t" +
rs.getString(3) + "t");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}