编写一个JDBC程序,要求如下: (1) 驱动程序:com.mysql.jdbc.Driver url:jdbc:mysql://localhost:3306/mydb?characterEncoding=utf8 用户名:root 密码:root 表信息:student(学号,姓名,年龄,成绩) (2)向student表中插入一条记录(1,孙悟空,500,89.8) (3)查询并显示student表中的所有记录。
时间: 2023-12-10 08:41:25 浏览: 28
以下是一个简单的JDBC程序,满足您的要求:
```java
import java.sql.*;
public class JDBCExample {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try {
// 注册 JDBC 驱动
Class.forName("com.mysql.jdbc.Driver");
// 打开连接
System.out.println("连接数据库...");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb?characterEncoding=utf8", "root", "root");
// 执行插入操作
System.out.println("向student表中插入一条记录...");
stmt = conn.createStatement();
String sql = "INSERT INTO student (id, name, age, score) VALUES (1, '孙悟空', 500, 89.8)";
stmt.executeUpdate(sql);
// 查询所有记录
System.out.println("查询student表中的所有记录...");
sql = "SELECT id, name, age, score FROM student";
ResultSet rs = stmt.executeQuery(sql);
// 显示查询结果
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
double score = rs.getDouble("score");
System.out.println("学号: " + id + ", 姓名: " + name + ", 年龄: " + age + ", 成绩: " + score);
}
// 清理环境
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("程序执行完毕!");
}
}
```