2024-12-21 01:22:44 +08:00
|
|
|
package example.dao;
|
|
|
|
|
|
|
|
import example.model.Computer;
|
|
|
|
import example.utils.DBUtils;
|
|
|
|
import org.apache.commons.dbutils.QueryRunner;
|
2024-12-21 01:58:50 +08:00
|
|
|
import org.apache.commons.dbutils.handlers.BeanHandler;
|
2024-12-21 01:22:44 +08:00
|
|
|
import org.apache.commons.dbutils.handlers.BeanListHandler;
|
|
|
|
|
|
|
|
import java.sql.SQLException;
|
|
|
|
import java.util.List;
|
|
|
|
|
|
|
|
public class ComputerDao {
|
|
|
|
private final QueryRunner queryRunner = new QueryRunner(DBUtils.getDataSource());
|
|
|
|
|
|
|
|
public int addComputer(String name, Double price, int stock) {
|
|
|
|
String sql = "insert into computer(name, price, stock) values(?, ?, ?)";
|
|
|
|
try {
|
|
|
|
return queryRunner.update(sql, name, price, stock);
|
|
|
|
} catch (Exception e) {
|
|
|
|
e.printStackTrace();
|
|
|
|
}
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
public int updateComputer(String name, Double price, int stock, int id) {
|
|
|
|
String sql = "update computer set name=?, price=?, stock=? where id=?";
|
|
|
|
try {
|
|
|
|
return queryRunner.update(sql, name, price, stock, id);
|
|
|
|
} catch (Exception e) {
|
|
|
|
e.printStackTrace();
|
|
|
|
}
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2024-12-21 01:27:15 +08:00
|
|
|
public void deleteComputer(int id) {
|
2024-12-21 01:22:44 +08:00
|
|
|
String sql = "delete from computer where id=?";
|
|
|
|
try {
|
2024-12-21 01:27:15 +08:00
|
|
|
queryRunner.update(sql, id);
|
2024-12-21 01:22:44 +08:00
|
|
|
} catch (Exception e) {
|
|
|
|
e.printStackTrace();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public List<Computer> getAllComputer() throws SQLException {
|
|
|
|
String sql = "select * from computer";
|
|
|
|
return queryRunner.query(sql,new BeanListHandler<>(Computer.class));
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2024-12-21 01:58:50 +08:00
|
|
|
public Computer getComputerById(int i) {
|
|
|
|
String sql = "select * from computer where id=?";
|
|
|
|
try {
|
|
|
|
return queryRunner.query(sql, new BeanHandler<>(Computer.class), i);
|
|
|
|
} catch (Exception e) {
|
|
|
|
e.printStackTrace();
|
|
|
|
}
|
|
|
|
return null;
|
|
|
|
}
|
2024-12-21 01:22:44 +08:00
|
|
|
}
|