当前位置:Gxlcms > 数据库问题 > 00311_预处理对象executeUpdate方法(实现数据库的增、删、改)

00311_预处理对象executeUpdate方法(实现数据库的增、删、改)

时间:2021-07-01 10:21:17 帮助过:55人阅读

import java.sql.Connection; 2 import java.sql.DriverManager; 3 import java.sql.PreparedStatement; 4 5 public class Demo01 { 6 public static void main(String[] args) throws Exception { 7 // 1注册驱动 8 Class.forName("com.mysql.jdbc.Driver"); 9 // 2获取连接 10 Connection conn = DriverManager.getConnection( 11 "jdbc:mysql://localhost:3306/mybase", "root", "root"); 12 // 3获得预处理对象 13 String sql = "insert into sort(sname) values(?)"; 14 PreparedStatement stat = conn.prepareStatement(sql); 15 // 4 SQL语句占位符设置实际参数 16 stat.setString(1, "空调"); 17 // 5执行SQL语句 18 int line = stat.executeUpdate(); 19 System.out.println("新添加记录数:" + line); 20 // 6释放资源 21 stat.close(); 22 conn.close(); 23 24 } 25 }

  运行结果:

  技术分享图片

  技术分享图片

3、更新记录:update,实现更新分类表中指定分类ID所对应记录的分类名称

 1 import java.sql.Connection;
 2 import java.sql.DriverManager;
 3 import java.sql.PreparedStatement;
 4 
 5 public class Demo02 {
 6     public static void main(String[] args) throws Exception {
 7         // 1注册驱动
 8         Class.forName("com.mysql.jdbc.Driver");
 9         // 2获取连接
10         Connection conn = DriverManager.getConnection(
11                 "jdbc:mysql://localhost:3306/mybase", "root", "root");
12         // 3获得预处理对象中
13         String sql = "update sort set sname=? where sid=?";
14         PreparedStatement stat = conn.prepareStatement(sql);
15         // 4 SQL语句占位符设置实际参数
16         stat.setString(1, "数码产品");
17         stat.setInt(2, 1);// 后面这个1是指sid
18         // 5执行SQL语句
19         int line = stat.executeUpdate();
20         System.out.println("更新记录数:" + line);
21         // 6释放资源
22         stat.close();
23         conn.close();
24 
25     }
26 }

  运行结果:“家电”更新为“数码产品”

  技术分享图片

4、删除记录:delete,实现删除分类表中指定分类ID的记录

 1 import java.sql.Connection;
 2 import java.sql.DriverManager;
 3 import java.sql.PreparedStatement;
 4 
 5 public class Demo03 {
 6     public static void main(String[] args) throws Exception {
 7         // 1注册驱动
 8         Class.forName("com.mysql.jdbc.Driver");
 9         // 2获取连接
10         Connection conn = DriverManager.getConnection(
11                 "jdbc:mysql://localhost:3306/mybase", "root", "root");
12         // 3获得预处理对象
13         String sql = "delete from sort where sid=?";
14         PreparedStatement stat = conn.prepareStatement(sql);
15         // 4 SQL语句占位符设置实际参数
16         stat.setInt(1, 1);
17         // 5执行SQL语句
18         int line = stat.executeUpdate();
19         System.out.println("删除记录数:" + line);
20         // 6释放资源
21         stat.close();
22         conn.close();
23 
24     }
25 }

  运行结果:sid为1的商品删除了

  技术分享图片

    

00311_预处理对象executeUpdate方法(实现数据库的增、删、改)

标签:ati   statement   line   img   产品   host   mys   家电   sid   

人气教程排行