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