练习JDBC,本地mysql创建数据库ie2121,创建表格student,包含字段id, name, phone, score. 通过jdbc,插入一条数据并查询出来,然后修改score,再查询修改后的结果。
时间: 2023-06-05 11:05:00 浏览: 77
好的,这个问题属于技术问题。针对你的问题,我可以给你提供以下的 Java 代码参考:
```java
import java.sql.*;
public class JDBCExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/ie2121";
static final String USER = "yourusername";
static final String PASS = "yourpassword";
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(DB_URL, USER, PASS);
// 执行查询
System.out.println("实例化statement对象...");
stmt = conn.createStatement();
String sql;
sql = "INSERT INTO student (`id`, `name`, `phone`, `score`) VALUES (1, 'John', '123-456-7890', 90)";
stmt.executeUpdate(sql);
// 查询数据并输出
System.out.println("查询数据...");
sql = "SELECT id, name, phone, score FROM student";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
// 通过字段检索
int id = rs.getInt("id");
String name = rs.getString("name");
String phone = rs.getString("phone");
int score = rs.getInt("score");
// 输出数据
System.out.print("ID: " + id);
System.out.print(", 姓名: " + name);
System.out.print(", 电话: " + phone);
System.out.println(", 成绩: " + score);
}
// 修改数据
System.out.println("修改 John 的成绩...");
sql = "UPDATE student SET score = 85 WHERE name='John'";
stmt.executeUpdate(sql);
// 再次查询数据并输出
System.out.println("再次查询数据...");
sql = "SELECT id, name, phone, score FROM student WHERE name='John'";
rs = stmt.executeQuery(sql);
while (rs.next()) {
// 通过字段检索
int id = rs.getInt("id");
String name = rs.getString("name");
String phone = rs.getString("phone");
int score = rs.getInt("score");
// 输出数据
System.out.print("ID: " + id);
System.out.print(", 姓名: " + name);
System.out.print(", 电话: " + phone);
System.out.println(", 成绩: " + 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("Goodbye!");
}
}
}
```
运行这个程序后,你将在控制台输出以下内容:
```
连接数据库...
实例化statement对象...
查询数据...
ID: 1, 姓名: John, 电话: 123-456-7890, 成绩: 90
修改 John 的成绩...
再次查询数据...
ID: 1, 姓名: John, 电话: 123-456-7890, 成绩: 85
Goodbye!
```
请注意,这个程序需要你填写你自己电脑的 MySQL 数据库的地址、用户名和密码。如果你执行程序的时候不能连接到数据库,请检查这些信息是否正确。