導(dǎo)入數(shù)據(jù)包 . 需要包括含有需要進(jìn)行數(shù)據(jù)庫編程的JDBC類的包。大多數(shù)情況下,使用 import java.sql.* 就可以了.
注冊(cè)JDBC驅(qū)動(dòng)程序. 需要初始化驅(qū)動(dòng)程序,可以與數(shù)據(jù)庫打開一個(gè)通信通道。
打開連接. 需要使用DriverManager.getConnection() 方法創(chuàng)建一個(gè)Connection對(duì)象,它代表與數(shù)據(jù)庫的物理連接。
執(zhí)行查詢 . 需要使用類型聲明的對(duì)象建立并提交一個(gè)SQL語句到數(shù)據(jù)庫。
從結(jié)果集中提取數(shù)據(jù) . 要求使用適當(dāng)?shù)年P(guān)于ResultSet.getXXX()方法來檢索結(jié)果集的數(shù)據(jù)。
清理環(huán)境. 需要明確地關(guān)閉所有的數(shù)據(jù)庫資源相對(duì)依靠JVM的垃圾收集。
示例代碼:
這個(gè)范例的例子可以作為一個(gè)模板,在需要建立JDBC應(yīng)用程序。
基于對(duì)環(huán)境和數(shù)據(jù)庫安裝在前面的章節(jié)中做此示例代碼已寫入。
復(fù)制下面的例子FirstExample.java,編譯并運(yùn)行,如下所示:
public class FirstExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
現(xiàn)在來編譯上面的例子如下:
新聞熱點(diǎn)
疑難解答
圖片精選