W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
OceanBase Connector/J 支持 DML 操作和 DDL 操作來更改數(shù)據(jù)庫。
要執(zhí)行數(shù)據(jù)操作語言(DML)的 INSERT
或 UPDATE
操作,可以創(chuàng)建一個 Statement
對象或 PreparedStatement
對象??梢允褂?nbsp;PreparedStatement
對象運行帶有輸入?yún)?shù)集的語句。Connection
對象的 prepareStatement
方法可以定義一條語句并采用變量綁定參數(shù),返回帶有語句定義的 PreparedStatement
對象。
PreparedStatement
對象使用 setXXX
方法將數(shù)據(jù)綁定到準(zhǔn)備發(fā)送到數(shù)據(jù)庫的語句。
示例:使用 PreparedStatement
執(zhí)行 INSERT
操作將兩行數(shù)據(jù)添加到 customers
表中。
PreparedStatement ps = null;
try{
ps = conn.prepareStatement ("insert into customers (customerID, name) values (?, ?)");
ps.setInt (1, 150); // 第一個? 對應(yīng) customerID
ps.setString (2, "Adam"); // 第二個? 對應(yīng) name
ps.execute ();
ps.setInt (1, 207);
ps.setString (2, "Alice");
ps.execute ();
}
finally{
if(ps!=null)
ps.close();
}
要執(zhí)行數(shù)據(jù)定義語言(DDL)操作,可以創(chuàng)建一個 Statement
對象或 PreparedStatement
對象。
示例:使用 Statement
對象在數(shù)據(jù)庫中創(chuàng)建表。
//創(chuàng)建表 customers 以及 customerID 和 name 列
String query;
Statement st=null;
try{
query="create table customers " +
"(customerID int, " +
"name varchar(50))";
st = conn.createStatement();
st.executeUpdate(query);
}
finally{
//關(guān)閉 Statement
st.close();
}
如果涉及重新執(zhí)行 DDL 操作,那么在重新執(zhí)行該語句之前,必須重新進行準(zhǔn)備。
示例:在重新執(zhí)行之前準(zhǔn)備 DDL 語句。
PreparedStatement ps = null;
PreparedStatement ts = null;
try{
ps = conn.prepareStatement ("insert into customers(customerID, name) values (?, ?)");
// 添加新顧客 Adam,編號150
ps.setInt (1, 150); // 第一個? 對應(yīng) customerID
ps.setString (2, "Adam"); // 第二個? 對應(yīng) name
// 插入數(shù)據(jù)
ps.execute ();
ts = conn.prepareStatement("truncate table customers");
ts.executeUpdate();
// 添加新顧客 Alice,編號 207
ps.setInt (1, 207); // 第一個? 對應(yīng) customerID
ps.setString (2, "Alice"); // 第二個? 對應(yīng) name
// 插入數(shù)據(jù)
ps.execute ();
ts.close();
ts = conn.prepareStatement("truncate table customers");
ts.executeUpdate();
}
finally{
if(ps!=null)
// 關(guān)閉 Statement
ps.close();
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: