JDBC数据库增、删、改、查方法实现类
package daoMYSQL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import entity.Master;
import sql.MasterDao;
import connection.BaseDao;
/*
*PetDao 实现类(主人)
*/
public class PetDaoMYSQLImp extends BaseDao implements MasterDao{
//插入数据到主人表
public int insert(Master mt) {
String sql="INSERT INTO master (id,name,password,money) values(?,?,?,?)";
Object[] param={mt.getId(),mt.getName(),mt.getPassWord(),mt.getMoney()};
int result=this.exceuteUpdate(sql,param);
return result;
}
//删除表内容
public int del(Master mt) {
String sql="delete from master where id=?";
Object[] param={mt.getId()};
int result=this.exceuteUpdate(sql, param);
return result;
}
//更新主人表
public int update(Master mt) {
String sql="update master set password=123456,money=900 where id=?";
Object[] param={mt.getId()};
int result=this.exceuteUpdate(sql, param);
return result;
}
//按指定属性查询表的内容
public List<Master> findByType(int masterId) {
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
List<Master> list=new ArrayList<Master>(); //创建集合
try {
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/epet","root","root");
String sql="select MasterId,name,password,money "+"from master"+" where masterId=?";
pstmt=conn.prepareStatement(sql);
pstmt.setInt(1,masterId);
rs=pstmt.executeQuery();
System.out.println("主人的信息列表");
System.out.println("序号\t姓名\t密码\t元宝数\t");
while(rs.next()){
Master ms=new Master();
ms.setMasterId(rs.getInt("masterId"));
ms.setName(rs.getString("name"));
ms.setPassWord(rs.getString("password"));
ms.setMoney(rs.getInt("money"));
list.add(ms);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(Master master:list){
System.out.println(master.getMasterId()+"\t"+master.getName()+"\t"+master.getPassWord()+"\t"+master.getMoney());
}
return list;
}
}