将数据库名以及SQL语句传递给Query类的对象,用表格(student)显示查询到的记录。效果如图,运用查询整个表格,增加一行数据,删除第三行的信息,修改20230001李华的姓名为李磊,进行练习。 [图片]
时间: 2024-10-21 18:15:50 浏览: 17
在Java中,你可以通过创建一个`Query`类,该类接受数据库名、SQL语句作为构造函数参数,并封装相应的数据库操作方法。例如:
```java
import java.sql.*;
public class Query {
private String dbName;
private Connection conn;
public Query(String dbName, String sql) throws SQLException {
this.dbName = dbName;
// 这里假设我们有一个连接池或者已经初始化了JDBC连接
conn = DriverManager.getConnection("jdbc:mysql://localhost/" + dbName);
}
// 示例方法执行SQL查询
public ResultSet executeSelect(String query) throws SQLException {
Statement stmt = conn.createStatement();
return stmt.executeQuery(query);
}
// 添加新行
public void addRow(String studentTable, String newRow) throws SQLException {
String sqlAdd = "INSERT INTO " + studentTable + " VALUES (" + newRow + ")";
PreparedStatement pstmt = conn.prepareStatement(sqlAdd);
pstmt.executeUpdate();
}
// 删除行
public void deleteRow(int rowIndex, String tableName) throws SQLException {
String sqlDelete = "DELETE FROM " + tableName + " WHERE id=" + rowIndex;
PreparedStatement pstmt = conn.prepareStatement(sqlDelete);
pstmt.executeUpdate();
}
// 修改行
public void updateRow(String studentId, String newName, String tableName) throws SQLException {
String sqlUpdate = "UPDATE " + tableName + " SET name='" + newName + "' WHERE id=" + studentId;
PreparedStatement pstmt = conn.prepareStatement(sqlUpdate);
pstmt.executeUpdate();
}
// 关闭连接
public void close() throws SQLException {
conn.close();
}
}
```
为了练习上述功能,你可以这样做:
1. 初始化`Query`对象并查询所有学生数据:
```java
Query query = new Query("your_database_name", "SELECT * FROM student");
ResultSet rs = query.executeSelect("...");
```
2. 添加新学生信息:
```java
query.addRow("student", "id=20230002, name='张明', ...");
```
3. 删除第三行:
```java
query.deleteRow(3, "student");
```
4. 更新20230001的学生姓名:
```java
query.updateRow("20230001", "李磊", "student");
```
记得处理可能出现的异常,并在完成操作后关闭连接。
阅读全文