使用java连接Mysql 和Using JDBC Statement Objects to Execute SQL

使用java连接Mysql 和Using JDBC Statement Objects to Execute SQL

首先引入mysql-connector-javaXXXXX.jar的包:

项目test右键 Build Path> Add External Achives…..>选择mysql-connector-javaXXXXX.jar(已经下载)

[java]

  1. package test;  
  2.   
  3. import java.sql.Connection;  
  4. import java.sql.DriverManager;  
  5. import java.sql.ResultSet;  
  6. import java.sql.SQLException;  
  7. import java.sql.Statement;  
  8.   
  9.   
  10. // Notice, do not import com.mysql.jdbc.*  
  11. // or you will have problems!  
  12.   
  13.   
  14. public class LoadDriver {  
  15.     public static void main(String[] args) {  
  16.         Connection conn = null;  
  17.         Statement stmt= null;  
  18.         ResultSet rs = null;  
  19.           
  20.         try {  
  21.             // The newInstance() call is a work around for some  
  22.             // broken Java implementations  
  23.   
  24.   
  25.             Class.forName(“com.mysql.jdbc.Driver”).newInstance();  
  26.         } catch (Exception ex) {  
  27.             ex.printStackTrace();  
  28.         }  
  29.   
  30.         try {  
  31.             conn =  
  32.                DriverManager.getConnection(“jdbc:mysql://localhost/mydatabase?” +  
  33.                                            “user=root&password=root”);  
  34.             stmt= conn.createStatement();  
  35.             rs = stmt.executeQuery(“select * from dept”);  
  36.             while(rs.next()){  
  37.                 System.out.println(rs.getString(“name”));  
  38.             }  
  39.             // Do something with the Connection  
  40.         } catch (SQLException ex) {  
  41.             // handle any errors  
  42.             System.out.println(“SQLException: “ + ex.getMessage());  
  43.             System.out.println(“SQLState: “ + ex.getSQLState());  
  44.             System.out.println(“VendorError: “ + ex.getErrorCode());  
  45.         }finally{  
  46.             try{  
  47.                 if(rs != null){  
  48.                     rs.close();  
  49.                     rs = null;  
  50.                 }  
  51.                 if(stmt != null){  
  52.                     stmt.close();  
  53.                     stmt = null;  
  54.                 }  
  55.                 if(conn != null){  
  56.                     conn.close();  
  57.                     conn = null;  
  58.                 }  
  59.                   
  60.             } catch (SQLException e){  
  61.                 e.printStackTrace();  
  62.             }  
  63.         }  
  64.     }  

标签