OceanBase Connector/J 更改數(shù)據(jù)庫

2021-06-30 15:35 更新

OceanBase Connector/J 支持 DML 操作和 DDL 操作來更改數(shù)據(jù)庫。

DML 操作

要執(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();
}

DDL 操作

要執(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();
}
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號