自定义类名:UserDao数据库名:jdbc用户名及密码均为:root表名及字段:useridnamepasswordemail相关API:DriverManager、Connection、Statement、ResultSet在控制台输出user表所有记录效果如下: id name password email 1 zs 123456 zssinacom 2 lisi 123
以下是Java代码实现:
import java.sql.*;
public class UserDao { private static final String URL = "jdbc:mysql://localhost:3306/jdbc"; private static final String USERNAME = "root"; private static final String PASSWORD = "root";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
// 获取数据库连接
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
// 创建Statement对象
stmt = conn.createStatement();
// 执行查询语句
rs = stmt.executeQuery("SELECT * FROM user");
// 输出表头
System.out.println("| id | name | password | email |");
// 输出表格
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String password = rs.getString("password");
String email = rs.getString("email");
System.out.printf("| %d | %s | %s | %s |\n", id, name, password, email);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭资源
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
AI 优化版
原文地址:https://www.cveoy.top/t/topic/hwBV 著作权归作者所有。请勿转载和采集!