1.首先创建Maven文件
2.在pom.xml里添加代码,配置连接MySQL数据库所需要的配置文件。
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
</dependencies>
3.ctrl +shift +o安装包和依赖
或者右键单击reload project,选择如图
4.编辑Test代码
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Test {
public static void main(String[] args) {
try {
String url = "jdbc:mysql://localhost:3306/ceshi?useSSL=false";
String uname = "root"; // 用户名
String pwd = "123456"; // 密码
String sql = "select id, NAME, PASSWORD from u";
// 加载 MySQL 驱动
Class.forName("com.mysql.jdbc.Driver");
// 获取数据库连接
Connection conn = DriverManager.getConnection(url, uname, pwd);
// 创建 Statement 对象
Statement stmt = conn.createStatement();
// 执行查询
ResultSet rs = stmt.executeQuery(sql);
// 处理结果集
while (rs.next()) {
int id = rs.getInt("id");
String username = rs.getString("NAME");
String password = rs.getString("PASSWORD");
System.out.println("ID: " + id + ", Username: " + username + ", Password: " + password);
}
// 关闭资源
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
5.显示如图即成功