针对sakila数据库中的actor表(演员表),每个列的意义是: actor_id:主键,用于唯一标识表中的每个演员 first_name:演员的名字 last_name:演员的姓氏 last_update:该行已创建或最近更新的时间 创建窗口,Java针对该表的数据提供增删改查操作,要求操作习惯和细节与课堂练习中的city窗口保持一致。
时间: 2024-02-13 18:07:15 浏览: 144
好的,针对sakila数据库中的actor表,以下是Java实现增删改查操作的示例:
1. 查询所有演员的信息
```
String query = "SELECT * FROM actor";
try {
Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
int actorId = rs.getInt("actor_id");
String firstName = rs.getString("first_name");
String lastName = rs.getString("last_name");
Timestamp lastUpdate = rs.getTimestamp("last_update");
// 处理查询结果
}
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
```
2. 查询某个演员的信息
```
String query = "SELECT * FROM actor WHERE actor_id = ?";
try {
Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setInt(1, actorId);
ResultSet rs = pstmt.executeQuery();
if(rs.next()){
int actorId = rs.getInt("actor_id");
String firstName = rs.getString("first_name");
String lastName = rs.getString("last_name");
Timestamp lastUpdate = rs.getTimestamp("last_update");
// 处理查询结果
}
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
```
3. 添加一个新演员
```
String query = "INSERT INTO actor (first_name, last_name, last_update) VALUES (?, ?, NOW())";
try {
Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, firstName);
pstmt.setString(2, lastName);
int rowsInserted = pstmt.executeUpdate();
if(rowsInserted > 0){
// 处理插入成功的情况
}
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
```
4. 更新某个演员的信息
```
String query = "UPDATE actor SET first_name = ?, last_name = ?, last_update = NOW() WHERE actor_id = ?";
try {
Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, firstName);
pstmt.setString(2, lastName);
pstmt.setInt(3, actorId);
int rowsUpdated = pstmt.executeUpdate();
if(rowsUpdated > 0){
// 处理更新成功的情况
}
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
```
5. 删除某个演员的信息
```
String query = "DELETE FROM actor WHERE actor_id = ?";
try {
Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setInt(1, actorId);
int rowsDeleted = pstmt.executeUpdate();
if(rowsDeleted > 0){
// 处理删除成功的情况
}
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
```
需要注意的是,在实际开发中,需要先加载数据库驱动,例如:
```
Class.forName("com.mysql.jdbc.Driver");
```
另外,为了防止SQL注入,建议使用PreparedStatement代替Statement,并将输入参数进行验证和转义。
阅读全文