以下是示例,該示例使用PreparedStatement以及打開和關(guān)閉語句:
該示例代碼是根據(jù)前幾章中的環(huán)境和數(shù)據(jù)庫設(shè)置編寫的。
復(fù)制并粘貼以下示例到 JDBCExample.java 中,如下編譯并運行:
//步驟1. 導(dǎo)入所需的軟件包
import java.sql.*;
public class JDBCExample {
//JDBC驅(qū)動程序名稱和數(shù)據(jù)庫URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";
// 數(shù)據(jù)庫憑據(jù)
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
PreparedStatement stmt = null;
try{
//步驟2: 注冊 JDBC 驅(qū)動程序
Class.forName("com.mysql.jdbc.Driver");
//步驟3:打開連接
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//步驟4:執(zhí)行查詢
System.out.println("Creating statement...");
String sql = "UPDATE Employees set age=? WHERE id=?";
stmt = conn.prepareStatement(sql);
//將值綁定到參數(shù)中。
stmt.setInt(1, 35); // set age
stmt.setInt(2, 102); // set ID
//讓我們用ID=102更新記錄的年齡;
int rows = stmt.executeUpdate();
System.out.println("Rows impacted : " + rows );
//讓我們選擇所有的記錄并顯示它們。
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);
//步驟5:從結(jié)果集中提取數(shù)據(jù)
while(rs.next()){
//按列名檢索
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);
}
//第六步:清理環(huán)境
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//處理JDBC的錯誤
se.printStackTrace();
}catch(Exception e){
//處理 Class.forName 的錯誤
e.printStackTrace();
}finally{
//用于關(guān)閉資源的finally塊
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 JDBCExample現(xiàn)在讓我們編譯上面的示例,如下所示:
C:\>javac FirstExample.java C:\>
當(dāng)您運行FirstExample時,它將產(chǎn)生以下結(jié)果-
C:\>java FirstExample Connecting to database... Creating statement... ID: 100, Age: 18, First: Zara, Last: Ali ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal C:\>