2014年4月22日 星期二

【JDBC 02】查詢資料

import java.sql.*;

import com.mysql.jdbc.Statement;

public class DBConn3 {

 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()); 
  }
  
  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();
      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("資料庫連線失敗");
  }
 }

}

執行結果

沒有留言:

張貼留言