宠物管理系统java+mysql实现增删查改
时间: 2023-07-30 15:12:02 浏览: 113
好的,以下是Java + MySQL实现的宠物管理系统增删查改代码示例:
1. 增加宠物信息
```java
public void addPet(Pet pet) throws SQLException {
String sql = "INSERT INTO pet(name, type, age) VALUES (?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, pet.getName());
statement.setString(2, pet.getType());
statement.setInt(3, pet.getAge());
statement.execute();
}
```
2. 删除宠物信息
```java
public void deletePet(int id) throws SQLException {
String sql = "DELETE FROM pet WHERE id=?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, id);
statement.execute();
}
```
3. 查询宠物信息
```java
public List<Pet> queryPet(String name) throws SQLException {
List<Pet> pets = new ArrayList<>();
String sql = "SELECT * FROM pet WHERE name=?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, name);
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
Pet pet = new Pet();
pet.setId(resultSet.getInt("id"));
pet.setName(resultSet.getString("name"));
pet.setType(resultSet.getString("type"));
pet.setAge(resultSet.getInt("age"));
pets.add(pet);
}
return pets;
}
```
4. 修改宠物信息
```java
public void updatePet(Pet pet) throws SQLException {
String sql = "UPDATE pet SET name=?, type=?, age=? WHERE id=?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, pet.getName());
statement.setString(2, pet.getType());
statement.setInt(3, pet.getAge());
statement.setInt(4, pet.getId());
statement.executeUpdate();
}
```
以上代码仅为示例,实际开发中需要根据具体情况进行修改和完善。
阅读全文