04-JDBC连接MySQL数据库【修改数据】 一时失言乱红尘 2022-06-15 02:38 139阅读 0赞 **JDBC连接mysql–学习目录:** > 地址:[http://blog.csdn.net/baidu\_37107022/article/details/72600018][http_blog.csdn.net_baidu_37107022_article_details_72600018] # 1.实现修改步骤 # ![这里写图片描述][SouthEast] **前三个步骤:注册、获得连接,创建statement对象方法,见上一节:** **02-JDBC实战–JDBC查询数据库MySQL–[http://blog.csdn.net/baidu\_37107022/article/details/72597975][http_blog.csdn.net_baidu_37107022_article_details_72597975]** # 2.使用jdbc修改数据库中的数据 # **这里使用的是queryDemo数据库,表格为demo1student,表中数据如下:** ![这里写图片描述][SouthEast 1] **代码演示** import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Properties; import org.junit.Test; public class Test10 { //修改数据 @Test public void updateData(){ Connection connection=null; PreparedStatement ps=null; try { Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://localhost:3306/queryDemo"; Properties info=new Properties(); info.put("user", "root"); info.put("password", "123"); connection=DriverManager.getConnection(url, info); String sql="update demo1student set name=?,score=? where id between ? and ? "; ps=connection.prepareStatement(sql); ps.setString(1, "无名"); ps.setInt(2, 88); ps.setInt(3, 14); ps.setInt(4, 16); int num=ps.executeUpdate(); if(num>0){ //如果插入成功,则打印success System.out.println("Sucess"); }else{ //如果插入失败,则打印Failure System.out.println("Failure"); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { //5.关闭资源 if(connection!=null){ try { connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(ps!=null){ try { ps.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } **运行结果:** **1.运行前** ![这里写图片描述][SouthEast 2] **2.运行后** ![这里写图片描述][SouthEast 3] [http_blog.csdn.net_baidu_37107022_article_details_72600018]: http://blog.csdn.net/baidu_37107022/article/details/72600018 [SouthEast]: /images/20220615/e627ae3621a54c2780abc7f964359af0.png [http_blog.csdn.net_baidu_37107022_article_details_72597975]: http://blog.csdn.net/baidu_37107022/article/details/72597975 [SouthEast 1]: /images/20220615/a73281bab46d4f2995bb7050d8e18312.png [SouthEast 2]: /images/20220615/e3b2c93d9efa403baec117e84418d209.png [SouthEast 3]: /images/20220615/cda721ef2a14408bbcc9d818c36fc2d6.png
还没有评论,来说两句吧...