jdbc_0">1.jdbc连接数据库
https://blog.csdn.net/qq_45807943/article/details/117320758
2.连接查询
package com.JDBC;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class student {
static final String JDBC_DRIVER = "com.sql>mysql.cj.jdbc.Driver";
static final String DB_URL = "jdbc:sql>mysql://localhost:3306/vueblog?serverTimezone=UTC";
//vueblog为我使用的数据库名称,请根据个人情况自行修改
// 数据库的用户名与密码,需要根据本地MySQL数据库设置
static final String USER = "root";
static final String PASS = "947";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// 注册 JDBC 驱动
Class.forName(JDBC_DRIVER);
// 打开链接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 执行查询
stmt = conn.createStatement();
String sql;
sql = "SELECT id, name FROM student";
ResultSet rs = stmt.executeQuery(sql);
// 展开结果集数据库
while(rs.next()) {
// 通过字段检索
int id = rs.getInt("id");
String name = rs.getString("name");
// 输出数据
System.out.print("学号: " + id);
System.out.print(", 姓名: " + name);
System.out.print("\n");
}
// 完成后关闭
rs.close();
stmt.close();
conn.close();
} catch(SQLException se) {
// 处理 JDBC 错误
se.printStackTrace();
} catch(Exception e) {
// 处理 Class.forName 错误
e.printStackTrace();
}finally {
// 关闭资源
try {
if(stmt!=null) stmt.close();
} catch(SQLException se2){ }
try {
if(conn!=null) conn.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
System.out.println("数据读取结束!");
}
}