不廢話,上代碼
1 package com.ningmeng; 2 3 import java.sql.*; 4 5 /** 6 * 1:更改數據庫中的數據 7 * @author biexiansheng 8 * 9 */ 10 public class Test04 { 11 12 public static void main(String[] args) { 13 // TODO Auto-generated method stub 14 try { 15 Class.forName("com.mysql.jdbc.Driver");//加載數據庫驅動 16 System.out.println("加載數據庫驅動成功"); 17 String url="jdbc:mysql://localhost:3306/test";//聲明數據庫test的url 18 String user="root";//數據庫賬號 19 String password="123456";//數據庫密碼 20 //建立數據庫連接,獲得連接對象conn 21 Connection conn=DriverManager.getConnection(url, user, password); 22 System.out.println("連接數據庫成功"); 23 String sql="update users set age=20 where id=1 ";//生成一條mysql語句 24 Statement stmt=conn.createStatement();//創建一個Statement對象 25 stmt.executeUpdate(sql);//執行SQL語句 26 System.out.println("修改數據庫成功"); 27 conn.close(); 28 System.out.println("關閉數據庫成功"); 29 } catch (ClassNotFoundException e) { 30 // TODO Auto-generated catch block 31 e.printStackTrace(); 32 } catch (SQLException e) { 33 // TODO Auto-generated catch block 34 e.printStackTrace(); 35 } 36 37 38 } 39 40 }
結果如下
上圖對比代表修改成功,ok.
注意:
修改數據庫是數據庫操作必不可少的一部分,使用Statement接口中的excuteUpdate()方法可以修改數據表中的數據,也可以使用PreparedStatement接口中的excuteUpdate方法對數據庫中的表進行修改操作。
1 package com.ningmeng; 2 3 import java.sql.*; 4 5 /** 6 * @author biexiansheng 7 * 8 */ 9 public class Test05 { 10 11 public static void main(String[] args) { 12 // TODO Auto-generated method stub 13 try { 14 Class.forName("com.mysql.jdbc.Driver");//加載數據庫驅動 15 System.out.println("加載數據庫驅動成功"); 16 String url="jdbc:mysql://localhost:3306/test";//聲明數據庫test的url 17 String user="root";//數據庫賬號 18 String password="123456";//數據庫密碼 19 //建立數據庫連接,獲得連接對象conn 20 Connection conn=DriverManager.getConnection(url, user, password); 21 System.out.println("連接數據庫成功"); 22 23 String sql="update users set password=? where sex=? ";//生成一條mysql語句 24 PreparedStatement ps=conn.prepareStatement(sql);//創建PreparedStatement對象 25 ps.setString(1, "admin");//為第一個問號賦值 26 ps.setInt(2, 0);//為第二個問號賦值 27 int count=ps.executeUpdate();//執行sql語句 28 System.out.println("修改數據庫成功"); 29 conn.close(); 30 System.out.println("關閉數據庫成功"); 31 32 } catch (ClassNotFoundException e) { 33 // TODO Auto-generated catch block 34 e.printStackTrace(); 35 } catch (SQLException e) { 36 // TODO Auto-generated catch block 37 e.printStackTrace(); 38 } 39 40 } 41 42 }
上圖對比,可知已經修改完畢
如上所示修改數據是根據一定的條件進行修改,這個條件可以是固定的,也可以是一個范圍,分別是第一個,第二個案例。
第二個案例使用PreparedStatement接口中的executeUpdate()方法修改數據庫users表中的數據。(將所有性別為0的用戶密碼改為admin,需要注意的是,我得數據表創建的時候性別是int類型的,只有0,1,2三種進行代表,所以參考案例的需要注意一下代碼的修改)