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();
}