定义数据库操作类JdbcAccess定义getstudent实现指定学号查询学生信息
时间: 2023-08-16 21:08:12 浏览: 121
好的,下面是JdbcAccess类的定义以及getstudent方法的实现示例:
```java
import java.sql.*;
public class JdbcAccess {
private Connection conn;
private PreparedStatement pstmt;
private ResultSet rs;
// 构造方法,初始化数据库连接
public JdbcAccess() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "123456";
conn = DriverManager.getConnection(url, user, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 根据学号获取学生信息
public void getstudent(int id) {
try {
String sql = "SELECT * FROM student WHERE id = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
rs = pstmt.executeQuery();
while (rs.next()) {
System.out.println("id: " + rs.getInt("id"));
System.out.println("name: " + rs.getString("name"));
System.out.println("age: " + rs.getInt("age"));
System.out.println("gender: " + rs.getString("gender"));
System.out.println("major: " + rs.getString("major"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null) rs.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
在该类中,我们首先在构造方法中初始化数据库连接,然后在getstudent方法中执行SQL查询语句,并将查询结果输出到控制台。需要注意的是,在执行完SQL语句后,我们需要及时关闭ResultSet、PreparedStatement和Connection对象,以避免资源泄漏。
使用该类时,只需要创建一个JdbcAccess对象,然后调用getstudent方法即可。例如:
```java
JdbcAccess access = new JdbcAccess();
access.getstudent(123456);
```
这将会输出学号为123456的学生信息。
阅读全文