04-JDBC连接MySQL数据库【修改数据】
生活随笔
收集整理的這篇文章主要介紹了
04-JDBC连接MySQL数据库【修改数据】
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
JDBC連接mysql–學(xué)習(xí)目錄:
地址:http://blog.csdn.net/baidu_37107022/article/details/72600018
1.實(shí)現(xiàn)修改步驟
前三個(gè)步驟:注冊、獲得連接,創(chuàng)建statement對象方法,見上一節(jié):
02-JDBC實(shí)戰(zhàn)–JDBC查詢數(shù)據(jù)庫MySQL–http://blog.csdn.net/baidu_37107022/article/details/72597975
2.使用jdbc修改數(shù)據(jù)庫中的數(shù)據(jù)
這里使用的是queryDemo數(shù)據(jù)庫,表格為demo1student,表中數(shù)據(jù)如下:
代碼演示
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 {//修改數(shù)據(jù)@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.關(guān)閉資源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();}}}} }運(yùn)行結(jié)果:
1.運(yùn)行前
2.運(yùn)行后
總結(jié)
以上是生活随笔為你收集整理的04-JDBC连接MySQL数据库【修改数据】的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 03-JDBC连接MySQL数据库【插入
- 下一篇: 05-JDBC连接MySQL数据库【删除