2、定义数据库操作类JdbcAccess,定义三个方法: (1)getConnection():实现数据库的连接; (2)getStudent():指定学号,查询学生信息; (3)addStudent():将学生信息插入数据库。 3、定义主类,连接数据库、根据学号查询学生信息、插入学生信息等操作。
时间: 2024-01-18 15:02:35 浏览: 74
java程序设计及应用课程中数据库的作业
4星 · 用户满意度95%
好的,以下是对您的问题的回答:
首先,您需要创建一个数据库操作类 JdbcAccess,该类包含三个方法:getConnection()、getStudent() 和 addStudent()。
getConnection() 方法用于实现数据库连接,这可以通过 JDBC 的 DriverManager 类来实现。以下是该方法的示例代码:
```java
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/TEST";
String user = "root";
String password = "password";
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
```
getStudent() 方法用于根据指定的学号查询学生信息。以下是该方法的示例代码:
```java
public static void getStudent(String stuName) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = getConnection();
String sql = "select * from student where stu_name=?";
stmt = conn.prepareStatement(sql);
stmt.setString(1, stuName);
rs = stmt.executeQuery();
while (rs.next()) {
String name = rs.getString("stu_name");
String sex = rs.getString("stu_sex");
int age = rs.getInt("stu_age");
int score = rs.getInt("score");
System.out.println("Name: " + name + ", Sex: " + sex + ", Age: " + age + ", Score: " + score);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
addStudent() 方法用于将学生信息插入数据库。以下是该方法的示例代码:
```java
public static void addStudent(String stuName, String stuSex, int stuAge, int score) {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = getConnection();
String sql = "insert into student(stu_name, stu_sex, stu_age, score) values(?, ?, ?, ?)";
stmt = conn.prepareStatement(sql);
stmt.setString(1, stuName);
stmt.setString(2, stuSex);
stmt.setInt(3, stuAge);
stmt.setInt(4, score);
int count = stmt.executeUpdate();
System.out.println("插入" + count + "条记录");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
最后,您需要定义一个包含主方法的类,该方法连接到数据库并调用上述方法执行操作。以下是该类的示例代码:
```java
public class Main {
public static void main(String[] args) {
String stuName = "niuniu";
String stuSex = "男";
int stuAge = 15;
int score = 90;
// 插入学生信息
addStudent(stuName, stuSex, stuAge, score);
// 查询学生信息
getStudent(stuName);
}
}
```
希望这些代码能够回答您的问题。
阅读全文