注冊jdbc驅動程序的三種方式


1、比較常用
try{
        Class.forName("com.mysql.jdbc.Driver");//加載數據庫驅動
       String url="jdbc:mysql://localhost:3306/databasename";//數據庫連接子協議
       Connection conn=DriverManager.getConnection(url,"username","password");
       Statement stmt=conn.createStatement();
       ResultSet rs=stmt.executeQuery("select * from tablename");
       while(rs.next()){//不斷指向下一條記錄
            System.out.println("DeptNo:"+rs.getInt(1));
            System.out.println("\tDeptName:"+rs.getString(2));
            System.out.println("\tLOC:"+rs.getString(3));
}         
    rs.close();
    stmt.close();
    conn.close();
}catch(ClassNotFoundException e){
   System.out.println("找不到指定的驅動程序類!");
}catch(SQLException e){
    e.printStackTrace();
}
 
 
2、通過系統的屬性設置
try{
        System.setProperty("jdbc.driver","com.mysql.jdbc.Driver");//系統屬性指定數據庫驅動
       String url="jdbc:mysql://localhost:3306/databasename";//數據庫連接子協議
       Connection conn=DriverManager.getConnection(url,"username","password");
       Statement stmt=conn.createStatement();
       ResultSet rs=stmt.executeQuery("select * from tablename");
       while(rs.next()){//不斷指向下一條記錄
            System.out.println("DeptNo:"+rs.getInt(1));
            System.out.println("\tDeptName:"+rs.getString(2));
            System.out.println("\tLOC:"+rs.getString(3));
}         
    rs.close();
    stmt.close();
    conn.close();
}catch(SQLException e){
    e.printStackTrace();
}

 

3、看起來比較直觀的一種方式,注冊相應的db的jdbc驅動,3在編譯時需要導入對應的lib
try{
        new com.mysql.jdbc.Driver();//創建driver對象,加載數據庫驅動
       String url="jdbc:mysql://localhost:3306/databasename";//數據庫連接子協議
       Connection conn=DriverManager.getConnection(url,"username","password");
       Statement stmt=conn.createStatement();
       ResultSet rs=stmt.executeQuery("select * from tablename");
       while(rs.next()){//不斷指向下一條記錄
            System.out.println("DeptNo:"+rs.getInt(1));
            System.out.println("\tDeptName:"+rs.getString(2));
            System.out.println("\tLOC:"+rs.getString(3));
}         
    rs.close();
    stmt.close();
    conn.close();
}catch(SQLException e){
    e.printStackTrace();
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM