package py.db.com; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import com.mysql.jdbc.PreparedStatement; public class DB_update { public static void main(String[] args) { //TestUpdate(); TestUpdatePre(); } private static void TestUpdatePre() { // TODO Auto-generated method stub String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "uplooking"; String sql1 = "update emp set sal = sal + ? where empno = 7900"; String sql2 = "select ename from emp where hiredate<?"; String sql3 = "update emp set sal = sal + 120 where empno = 7900"; Connection conn = null; java.sql.PreparedStatement ps = null; try { //註冊並載入數據庫驅動 Class.forName("com.mysql.jdbc.Driver"); System.out.println("數據庫驅動加載成功..."); //創建數據庫鏈接 conn = DriverManager.getConnection(url, user, password); System.out.println("數據庫鏈接已創建..."); //準備一個處理器用來包裝sql代碼 ps = conn.prepareStatement(sql1); //設置參數 ps.setInt(1, 250); //執行sql代碼 int rs = ps.executeUpdate(); if (rs == 1) { System.out.println("數據庫sql執行成功."); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block System.out.println("數據庫驅動加載失敗"); e.printStackTrace(); } catch (SQLException e) { System.out.println("數據庫通信失敗"); //e.printStackTrace(); } finally { //關閉對象及鏈接 try { ps.close(); conn.close(); } catch (Exception e) { // TODO Auto-generated catch block System.out.println("對象關閉失敗"); //e.printStackTrace(); } } } private static void TestUpdate() { // TODO Auto-generated method stub String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "uplooking"; String sql1 = "select ename,empno from emp where empno=? and sal>?"; String sql2 = "select ename from emp where hiredate<?"; String sql3 = "update emp set sal = sal + 120 where empno = 7900"; Connection conn = null; Statement stmt = null; try { //註冊並載入數據庫驅動 Class.forName("com.mysql.jdbc.Driver"); System.out.println("數據庫驅動加載成功..."); //創建數據庫鏈接 conn = DriverManager.getConnection(url, user, password); System.out.println("數據庫鏈接已創建..."); //準備一個處理器用來包裝sql代碼 stmt = conn.createStatement(); //執行sql代碼 int rs = stmt.executeUpdate(sql3); if (rs == 1) { System.out.println("數據庫sql執行成功."); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block System.out.println("數據庫驅動加載失敗"); e.printStackTrace(); } catch (SQLException e) { System.out.println("數據庫通信失敗"); //e.printStackTrace(); } finally { //關閉對象及鏈接 try { stmt.close(); conn.close(); } catch (Exception e) { // TODO Auto-generated catch block System.out.println("對象關閉失敗"); //e.printStackTrace(); } } } }