2014年4月22日 星期二

【JDBC 03】異動資料:新㽪、修改、刪除


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import javax.swing.JOptionPane;

import com.mysql.jdbc.Statement;


public class DBConn4 {

 public static void main(String[] args) {
  try {
   Class.forName("com.mysql.jdbc.Driver");
   System.out.println("Success loading JDBC-ODBC Bridge Driver");
  } catch (ClassNotFoundException e){
   System.out.println("JDBC 沒有驅動程式" + e.getMessage()); 
  }
  
  int op = 0;
  String sqlstr ="",id="",name="";
  try {
   op = Integer.parseInt(JOptionPane.showInputDialog("請選擇選單\n1: 新增 2:修改 3:刪除"));
   
   switch(op){
   case 1:
    id = JOptionPane.showInputDialog("請輸入座號");
    name = JOptionPane.showInputDialog("請輸姓名").replace("'", "'");
    sqlstr = "INSERT INTO student(ID,name) VALUES (" +
              id  + ",'"+ name + "'" + ")";
    break;
   case 2:
    id = JOptionPane.showInputDialog("請輸入欲修改資料(以座號為依據)");
    name = JOptionPane.showInputDialog("請輸姓名").replace("'", "'");
    sqlstr = "UPDATE student SET name='" + name +"'" +
             "WHERE ID = "+ id;
    break;
   case 3:
    id = JOptionPane.showInputDialog("請輸入欲刪除資料(以座號為依據)");
    sqlstr = "DELETE FROM student WHERE ID="+id;
    break;
   default:
    System.out.println("Error");
   }
  }catch(NumberFormatException e){
   
  }
  
  
  try { 
   
      String url =  "jdbc:mysql://localhost:3306/phone?" + 
                    "user=root&password=12345"; 
      Connection conn = DriverManager.getConnection(url); 
      if(!conn.isClosed()) 
          System.out.println("資料庫連線成功"); 
      
      Statement sm = (Statement) conn.createStatement();
      if(op !=0){
       sm.execute(sqlstr);
      }
      
      ResultSet rs = sm.executeQuery("SELECT * FROM student");
      ResultSetMetaData rsmd = rs.getMetaData();
      for(int i=1; i <= rsmd.getColumnCount(); i++){
       System.out.print(rsmd.getColumnName(i)+"\t");
      }
      System.out.println("\n---------------------");
      while(rs.next()){
       System.out.print(rs.getInt(1) + "\t" +
                           rs.getString(2));
       System.out.println();
      }
      
            sm.close();
      conn.close(); 
  } 
  catch(SQLException e) { 
   System.out.println("資料庫連線失敗");
  }
 }

}


執行結果
新增
















修改
















刪除







2 則留言:

  1. 您好,請問我若要新增一個項目,例如性別sex,那我只需要照您程式碼上的樣子新增嗎?有什麼特別要注意的問題呢?感謝您

    回覆刪除
  2. 作者已經移除這則留言。

    回覆刪除