一:下载·MySQL connector java
https://dev.mysql.com/downloads/connector/j/,
解压后如图所示、
得到一个mysql-connector-java-8.0.28.jar
文件
二:打开project structure
,完成以下步骤添加mysql-connector-java-8.0.28.jar
文件
测试代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Main {
public static void main(String[] args) {
// 数据库URL
String url = "jdbc:mysql://localhost:3306/数据库名";
// 数据库用户名
String username = "用户名";
// 数据库密码
String password = "密码";
// 使用try-with-resources语句来自动关闭资源
try (
// 连接数据库
Connection conn = DriverManager.getConnection(url, username, password);
// 准备SQL语句
PreparedStatement statement = conn.prepareStatement("SELECT * FROM book");
) {
// 加载JDBC驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 执行查询
ResultSet resultSet = statement.executeQuery();
// 处理结果集
while (resultSet.next()) {
// 根据您的表结构,这里假设有id, title, author列
int id = resultSet.getInt("bid");
String title = resultSet.getString("bname");
String author = resultSet.getString("bauthor");
// 打印书籍信息
System.out.println("Book ID: " + id + ", Title: " + title + ", Author: " + author);
}
// 关闭结果集
resultSet.close();
} catch (ClassNotFoundException e) {
System.out.println("MySQL JDBC Driver not found.");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("Connection failure.");
e.printStackTrace();
}
}
}