您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
12-JDBC练习-添加&修改&删除(基于executeUpdate增删改封装)
发布时间:2024-11-15 17:16:36编辑:雪饮阅读()
-
其实数据的增删改只是执行的sql不同,都可以共同使用PreparedStatement的函数
executeUpdate
这里对原本讲的内容的一个封装,从0,1,2中随机,如果随机为0则表示新增数据,如果随机为1则表示删除数据,如果随机是2表示修改数据。
则基于上篇,实现如
@Test
public void testAddDelUpdate() throws Exception {
Properties prop=new Properties();
prop.load(new FileInputStream(System.getProperty("user.dir")+"\\src\\druid.properties"));
DataSource dataSource= DruidDataSourceFactory.createDataSource(prop);
Connection conn= dataSource.getConnection();
//假定0为增加,1为删除,2为新增
Random random = new Random();
int type = random.nextInt(3);
String sql10="";
String brand_name="三只松鼠";
String company_name="三只松鼠股份有限公司";
int ordered=0;
String description="好吃不上火";
int status=0;
Statement stmt=null;
PreparedStatement pstmt=null;
ResultSet rs=null;
//获取最新id
stmt=conn.createStatement();
rs=stmt.executeQuery("select * from tb_brand order by id desc");
rs.next();
int latestId=rs.getInt("id");
//增加
if(type==0){
sql10="insert into tb_brand (brand_name, company_name, ordered, description, status) values (?,?,?,?,?)";
pstmt=conn.prepareStatement(sql10);
pstmt.setString(1,brand_name);
pstmt.setString(2,company_name);
pstmt.setInt(3,ordered);
pstmt.setString(4,description);
pstmt.setInt(5,status);
pstmt.executeUpdate();
//获取新增id
stmt=conn.createStatement();
rs=stmt.executeQuery("select * from tb_brand order by id desc");
rs.next();
int id=rs.getInt("id");
System.out.println("新增数据成功,数据id:"+id);
}
//删除
if(type==1){
//删除最新数据
sql10="delete from tb_brand where id=?";
pstmt=conn.prepareStatement(sql10);
pstmt.setInt(1,latestId);
pstmt.executeUpdate();
System.out.println("删除数据成功,数据id:"+latestId);
}
//修改
if(type==2){
sql10="update tb_brand set brand_name=?,company_name=?,ordered=?,description=?, status=? where id=?";
pstmt=conn.prepareStatement(sql10);
pstmt.setString(1,brand_name+latestId);
pstmt.setString(2,company_name+latestId);
pstmt.setInt(3,ordered+latestId);
pstmt.setString(4,description+latestId);
pstmt.setInt(5,status);
pstmt.setInt(6,latestId);
pstmt.executeUpdate();
System.out.println("数据修改成功,数据id:"+latestId);
}
if(rs!=null){
rs.close();
}
if(stmt!=null){
stmt.close();
}
if(conn!=null){
conn.close();
}
}
关键字词:executeUpdate,jdbc,增删改