1,、創(chuàng)建 Statement 對象
建立了到特定數(shù)據(jù)庫的連接之后,就可用該連接發(fā)送 SQL 語句。
Statement 對象用 Connection 的方法 createStatement 創(chuàng)建,,如下列代碼段中所示:
String sql = String.format("INSERT INTO %s ( %s ) VALUES ( %s )", table_A, AttList.toString(), ValList.toString())
Class.forName("com.ibm.db2.jdbc.app.DB2Driver ").newInstance();
String url="jdbc:db2://localhost:5000/DBserverName";
//DBserverName為你的數(shù)據(jù)庫名
String user="admin";
String password="";
Connection m_lblDBconn = DriverManager.getConnection(url, user, password);
Statement SQLDBStm = m_lblDBconn.createStatement();
//驅(qū)動數(shù)據(jù)庫廠商就是根據(jù)JDBC的接口規(guī)范編寫的實現(xiàn)類 當你加載注冊一個數(shù)據(jù)庫的驅(qū)動后 進行數(shù)據(jù)庫操作時,就會生成驅(qū)動里面的具體類的對象
然后通過一個接口引用指向這個對象m_lblDBconn Statement SQLDBStm =
m_lblDBconn.createStatement() 你可以通過rtti得到獲得具體對象
為了執(zhí)行 Statement 對象,,被發(fā)送到數(shù)據(jù)庫的 SQL 語句將被作為參數(shù)提供給 Statement 的方法:
int ID = -1;
SQLDBStm.executeUpdate( sql, Statement.RETURN_GENERATED_KEYS);
我們通過以下方法獲得新增數(shù)據(jù)的主鍵值
ResultSet rs = SQLDBStm.getGeneratedKeys();
rs.first();
if (rs.next()){
ID = rs.getInt(1); //Obtain the new ID;
}
return Integer.toString(ID);
這里我們使用了獲得自動生成主鍵的方法executeUpdate( sql, Statement.RETURN_GENERATED_KEYS);并使用getGeneratedKeys()
返回Id值
2、使用 Statement 對象執(zhí)行語句
Statement 接口提供了三種執(zhí)行 SQL 語句的方法:executeQuery,、executeUpdate 和 execute,。使用哪一個方法由 SQL 語句所產(chǎn)生的內(nèi)容決定。
方法 executeQuery 用于產(chǎn)生單個結(jié)果集的語句,,例如 SELECT 語句,。
方
法 executeUpdate 用于執(zhí)行 INSERT、UPDATE 或 DELETE 語句以及 SQL DDL(數(shù)據(jù)定義語言)語句,,例如
CREATE TABLE 和 DROP TABLE,。INSERT、UPDATE 或 DELETE
語句的效果是修改表中零行或多行中的一列或多列,。executeUpdate 的返回值是一個整數(shù),,指示受影響的行數(shù)(即更新計數(shù))。對于 CREATE
TABLE 或 DROP TABLE 等不操作行的語句,,executeUpdate 的返回值總為零,。
方法 execute 用于執(zhí)行返回多個結(jié)果集、多個更新計數(shù)或二者組合的語句,。因為多數(shù)程序員不會需要該高級功能,,所以本概述后面將在單獨一節(jié)中對其進行介紹。
執(zhí)行語句的所有方法都將關(guān)閉所調(diào)用的 Statement 對象的當前打開結(jié)果集(如果存在),。這意味著在重新執(zhí)行 Statement 對象之前,,需要完成對當前 ResultSet 對象的處理。
應
注意,,繼承了 Statement 接口中所有方法的 PreparedStatement 接口都有自己的
executeQuery,、executeUpdate 和 execute 方法。Statement 對象本身不包含 SQL 語句,,因而必須給
Statement.execute 方法提供 SQL 語句作為參數(shù),。PreparedStatement 對象并 不將 SQL
語句作為參數(shù)提供給這些方法,因為它們已經(jīng)包含預編譯 SQL 語句,。CallableStatement 對象繼承這些方法的
PreparedStatement 形式,。對于這些方法的 PreparedStatement 或 CallableStatement
版本,使用查詢參數(shù)將拋出 SQLException,。
3、語句完成
當連接處于自動提交模式時,,其中所執(zhí) 行的語句在完成時將自動提交或還原,。語句在已執(zhí)行且所有結(jié)果返回時,即認為已完成。對于返回一個結(jié)果集的
executeQuery 方法,,在檢索完 ResultSet 對象的所有行時該語句完成,。對于方法
executeUpdate,當它執(zhí)行時語句即完成,。但在少數(shù)調(diào)用方法 execute 的情況中,,在檢索所有結(jié)果集或它生成的更新計數(shù)之后語句才完成。
4,、關(guān)閉 Statement 對象
Statement 對象將由 Java 垃圾收集程序自動關(guān)閉,。而作為一種好的編程風格,應在不需要 Statement 對象時顯式地關(guān)閉它們,。這將立即釋放 DBMS 資源,,有助于避免潛在的內(nèi)存問題。
statement-相關(guān)概述
Statement 對象用于將 SQL 語句發(fā)送到數(shù)據(jù)庫中,。實際上有三種 Statement 對象,,它們都作為在給定連接上執(zhí)行
SQL
語句的包容器:Statement、PreparedStatement(它從 Statement 繼承而來)和
CallableStatement(它從 PreparedStatement 繼承而來),。它們都專用于發(fā)送特定類型的 SQL 語句:
Statement 對象用于執(zhí)行不帶參數(shù)的簡單 SQL 語句,;PreparedStatement 對象用于執(zhí)行帶或不帶 IN 參數(shù)的預編譯
SQL 語句;CallableStatement 對象用于執(zhí)行對數(shù)據(jù)庫已存儲過程的調(diào)用,。
Statement 接口提供了執(zhí)行語句和獲取結(jié)果的基本方法,。PreparedStatement 接口添加了處理 IN 參數(shù)的方法;而 CallableStatement 添加了處理 OUT 參數(shù)的方法,。
有些 DBMS 將已存儲過程中的每條語句視為獨立的語句,;而另外一些則將整個過程視為一個復合語句。在啟用自動提交時,,這種差別就變得非常重要,,因為它影響什么時候調(diào)用 commit 方法。在前一種情況中,,每條語句單獨提交,;在后一種情況中,所有語句同時提交,。
JDBC 3種獲得mysql插入數(shù)據(jù)的自增字段值的方法
1. Retrieving AUTO_INCREMENT Column Values using Statement.getGeneratedKeys()
2. Retrieving AUTO_INCREMENT Column Values using SELECT LAST_INSERT_ID()
3. Retrieving AUTO_INCREMENT Column Values in Updatable ResultSets
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class RetrievAutoIncrementTest {
public void init() throws Exception {
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager
.getConnection("jdbc:mysql://localhost/test?","root", "admin");
// Issue the DDL queries for the table for this example
stmt = conn.createStatement();
stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTutorial");
//創(chuàng)建數(shù)據(jù)庫表autoIncTutorial,。
stmt.executeUpdate("CREATE TABLE autoIncTutorial ("
+ "priKey INT NOT NULL AUTO_INCREMENT, "
+ "dataField VARCHAR(64), PRIMARY KEY (priKey))");
} finally {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
}
}
if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
}
}
}
}
方法1:
public void test1() throws Exception {
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager
.getConnection("jdbc:mysql://localhost:3306/test","root", "admin");
// Create a Statement instance that we can use for
// 'normal' result sets assuming you have a
// Connection 'conn' to a MySQL database already available
stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_UPDATABLE);
//Insert one row that will generate an AUTO INCREMENT key in the 'priKey' field
for (int i = 0; i < 10; i++) {
stmt.executeUpdate("INSERT INTO autoIncTutorial (dataField) "
+ "values ('Can I Get the Auto Increment Field?')",
Statement.RETURN_GENERATED_KEYS);
// Example of using Statement.getGeneratedKeys()
// to retrieve the value of an auto-increment value
int autoIncKeyFromApi = -1;
rs = stmt.getGeneratedKeys();
if (rs.next()) {
autoIncKeyFromApi = rs.getInt(1);
} else {
// throw an exception from here
}
rs.close();
rs = null;
System.out.println("Key returned from getGeneratedKeys():"
+ autoIncKeyFromApi);
}
} finally {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
}
}
if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
}
}
}
}
方法2:
public void test2() throws Exception {
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
//
// Create a Statement instance that we can use for
// 'normal' result sets.
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager
.getConnection("jdbc:mysql://localhost/test","root", "admin");
stmt = conn.createStatement();
// Insert one row that will generate an AUTO INCREMENT
// key in the 'priKey' field
for (int i = 0; i < 10; i++) {
stmt.executeUpdate("INSERT INTO autoIncTutorial (dataField) "
+ "values ('Can I Get the Auto Increment Field?')");
// Use the MySQL LAST_INSERT_ID() function to do the same thing as getGeneratedKeys()
int autoIncKeyFromFunc = -1;
rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");
if (rs.next()) {
autoIncKeyFromFunc = rs.getInt(1);
} else {
// throw an exception from here
}
rs.close();
System.out.println("Key returned from "
+ "'SELECT LAST_INSERT_ID()': " + autoIncKeyFromFunc);
}
} finally {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
}
}
if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
}
}
}
}
方法3:
public void test3() throws Exception {
Statement stmt = null;
ResultSet rs = null;
Connection conn = null;
try {
// Create a Statement instance that we can use for
// 'normal' result sets as well as an 'updatable'
// one, assuming you have a Connection 'conn' to a MySQL database already available
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager
.getConnection("jdbc:mysql://localhost/test","root", "admin");
stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_UPDATABLE);
for (int i = 0; i < 10; i++) {
// Example of retrieving an AUTO INCREMENT key from an updatable result set
rs = stmt.executeQuery("SELECT priKey, dataField "+ "FROM autoIncTutorial");
rs.moveToInsertRow();
rs.updateString("dataField", "AUTO INCREMENT here?");
rs.insertRow();
// the driver adds rows at the end
rs.last();
// We should now be on the row we just inserted
int autoIncKeyFromRS = rs.getInt("priKey");
rs.close();
rs = null;
System.out.println("Key returned for inserted row: "+ autoIncKeyFromRS);
}
} finally {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
}
}
if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
}
}
}
}
public static void main(String[] args) throws Exception {
RetrievAutoIncrementTest test = new RetrievAutoIncrementTest();
test.init();
test.test1(); //測試第一種獲取自增字段的值
test.test2(); //測試第二種獲取自增字段的值
test.test3(); //測試第三種獲取自增字段的值
}
}
參考文獻:
[1] 三種獲得自動生成主鍵的方法,getGeneratedKeys,專用SQL和可更新的結(jié)果集
http://blog.csdn.net/java2000_net/archive/2008/09/27/2989625.aspx
[2] java Statement詳細用法
http://hi.baidu.com/shifeng121/blog/item/0a38c3588e5fa589810a18c7.html