開發(fā)應用程序時宪拥,經常需要操作數(shù)據(jù)庫奸攻。
Java中操作數(shù)據(jù)庫常需要以下步驟:
- 加載數(shù)據(jù)庫驅動:
class.forName(driver);
driver就是數(shù)據(jù)庫的驅動類稍算,MySQL的是"com.mysql.jdbc.Driver",Oracle的是"oracle.jdbc.driver.OracleDriver" - 連接數(shù)據(jù)庫墨技,使用
DriverManager.getConnection(url,user,password);
方法連接 - 創(chuàng)建statement對象執(zhí)行SQL語句
- 創(chuàng)建ResultSet類對象惩阶,存放獲取的結果集
- 關閉結果集
- 斷開和數(shù)據(jù)庫連接
步驟比較簡略,下面是一個實例:
//聲明Connection對象
Connection con=null;
//驅動類名
String driver="com.mysql.jdbc.Driver";
/*
URL,指向要訪問的數(shù)據(jù)庫名稱,
jdbc:mysql是固定寫法扣汪,
localhost是本機断楷,可換成ip地址,
3306是默認端口號崭别,
shoot是數(shù)據(jù)庫名稱
*/
String url="jdbc:mysql://localhost:3306/shoot";
//Mysql用戶名
String user="admin";
String password="admin";
//使用Class.forName()方法加載驅動時冬筒,會產生ClassNotFoundException,使用時需要對其進行異常處理
try{
//加載驅動
class.forName(driver);
//連接數(shù)據(jù)庫
con=DriverManager.getConnection(url,user,password);
if(!con.isClosed){
System.out.println("Succeeded connection to the DataBase!");
//創(chuàng)建Statement對象,執(zhí)行SQL語句
Statement statement=con.createStatement();
String sql="select * from emp";
//創(chuàng)建ResultSet類茅主,存放獲取的結果
ResultSet rs=statement.executeQuery(sql);
System.out.println("查詢結果:");
String job=null;
String id=null;
while (rs.next()) {
job=rs.getString("job");
id=rs.getString("ename");
//輸出結果
System.out.println(id+"\t"+job);
}
//斷開連接
rs.close();
con.close();
}
}catch(ClassNotFoundException e){
e.printStackTrace();
}