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在編譯時間需要匯入對應的libtry{ 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();}