04-JDBC连接MySQL数据库【修改数据】
生活随笔
收集整理的這篇文章主要介紹了
04-JDBC连接MySQL数据库【修改数据】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
JDBC連接mysql–學習目錄:
地址:http://blog.csdn.net/baidu_37107022/article/details/72600018
1.實現修改步驟
前三個步驟:注冊、獲得連接,創建statement對象方法,見上一節:
02-JDBC實戰–JDBC查詢數據庫MySQL–http://blog.csdn.net/baidu_37107022/article/details/72597975
2.使用jdbc修改數據庫中的數據
這里使用的是queryDemo數據庫,表格為demo1student,表中數據如下:
代碼演示
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 {//修改數據@Testpublic 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){//如果插入成功,則打印successSystem.out.println("Sucess");}else{//如果插入失敗,則打印FailureSystem.out.println("Failure");}} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally {//5.關閉資源if(connection!=null){try {connection.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}if(ps!=null){try {ps.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}} }運行結果:
1.運行前
2.運行后
總結
以上是生活随笔為你收集整理的04-JDBC连接MySQL数据库【修改数据】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 03-JDBC连接MySQL数据库【插入
- 下一篇: 05-JDBC连接MySQL数据库【删除