用java创建一学生数据库School,创建一表studb,包含字段:学号、姓名、性别、专业、入学年份。编写程序对studb表进行学生信息的增、删、改、查操作。
时间: 2023-10-18 09:04:34 浏览: 133
好的,下面是使用Java语言实现对studb表进行学生信息增删改查操作的示例代码:
```java
import java.sql.*;
public class StudentDatabase {
public static void main(String[] args) {
//数据库连接参数
String url = "jdbc:mysql://localhost:3306/School?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
String user = "root";
String password = "password";
try {
//加载MySQL JDBC驱动程序
Class.forName("com.mysql.jdbc.Driver");
//创建数据库连接对象
Connection conn = DriverManager.getConnection(url, user, password);
//创建Statement对象
Statement stmt = conn.createStatement();
//创建studb表
String createTableSql = "CREATE TABLE IF NOT EXISTS studb (id INT PRIMARY KEY, name VARCHAR(20), gender VARCHAR(10), major VARCHAR(20), enrollment INT)";
stmt.executeUpdate(createTableSql);
//插入数据
String insertSql = "INSERT INTO studb VALUES (1, '小明', '男', '计算机科学与技术', 2020)";
stmt.executeUpdate(insertSql);
System.out.println("插入数据成功");
//查询数据
String querySql = "SELECT * FROM studb";
ResultSet rs = stmt.executeQuery(querySql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
String major = rs.getString("major");
int enrollment = rs.getInt("enrollment");
System.out.println("id=" + id + ", name=" + name + ", gender=" + gender + ", major=" + major + ", enrollment=" + enrollment);
}
//更新数据
String updateSql = "UPDATE studb SET name = '小红', gender = '女', major = '软件工程', enrollment = 2021 WHERE id = 1";
stmt.executeUpdate(updateSql);
System.out.println("更新数据成功");
//查询数据
rs = stmt.executeQuery(querySql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
String major = rs.getString("major");
int enrollment = rs.getInt("enrollment");
System.out.println("id=" + id + ", name=" + name + ", gender=" + gender + ", major=" + major + ", enrollment=" + enrollment);
}
//删除数据
String deleteSql = "DELETE FROM studb WHERE id = 1";
stmt.executeUpdate(deleteSql);
System.out.println("删除数据成功");
//查询数据
rs = stmt.executeQuery(querySql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String gender = rs.getString("gender");
String major = rs.getString("major");
int enrollment = rs.getInt("enrollment");
System.out.println("id=" + id + ", name=" + name + ", gender=" + gender + ", major=" + major + ", enrollment=" + enrollment);
}
//关闭数据库连接
rs.close();
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
上述代码中,使用了JDBC的方式连接MySQL数据库,并创建了Statement对象。然后创建了studb表,插入数据、查询数据、更新数据和删除数据等操作。最后关闭了数据库连接。如果需要使用该程序进行实际操作,需要根据实际情况修改数据库连接参数和数据操作逻辑。
阅读全文