首批通过分布式安全可靠测评,为关键业务系统打造
管理表和数据
更新时间:2026-05-08 16:10:59
OceanBase Connector/J 支持 DML 操作和 DDL 操作来更改数据库的表和数据。
DML 操作
要执行数据操作语言(DML)的 INSERT 或 UPDATE 操作,可以创建一个 Statement 对象或 PreparedStatement 对象。可以使用 PreparedStatement 对象运行带有输入参数集的语句。Connection 对象的 prepareStatement 方法可以定义一条语句并采用变量绑定参数,返回带有语句定义的 PreparedStatement 对象。
PreparedStatement 对象使用 setXXX 方法将数据绑定到准备发送到数据库的语句。
示例:使用 PreparedStatement 执行 INSERT 操作将两行数据添加到 customers 表中。
PreparedStatement ps = null;
try{
ps = conn.prepareStatement ("insert into customers (customerID, name) values (?, ?)");
ps.setInt (1, 150); // 第一个? 对应 customerID
ps.setString (2, "Adam"); // 第二个? 对应 name
ps.execute ();
ps.setInt (1, 207);
ps.setString (2, "Alice");
ps.execute ();
}
finally{
if(ps!=null)
ps.close();
}
DDL 操作
要执行数据定义语言(DDL)操作,可以创建一个 Statement 对象或 PreparedStatement 对象。
示例:使用 Statement 对象在数据库中创建表。
//创建表 customers 以及 customerID 和 name 列
String query;
Statement st=null;
query="create table customers " +
"(customerID int, " +
"name varchar(50))";
st = conn.createStatement();
st.executeUpdate(query);
st.close(); //关闭 Statement
如果涉及重新执行 DDL 操作,那么在重新执行该语句之前,必须重新 Prepare。
示例:在重新执行之前准备 DDL 语句。
PreparedStatement ps = null;
PreparedStatement ts = null;
ps = conn.prepareStatement ("insert into customers(customerID, name) values (?, ?)"); // 第一个? 对应 customerID,第二个? 对应 name
ps.setInt (1, 150); // 添加新顾客 Adam,编号 150
ps.setString (2, "Adam");
ps.execute ();
ts = conn.prepareStatement("truncate table customers");
ts.executeUpdate();
ps.setInt (1, 207); // 添加新顾客 Alice,编号 207
ps.setString (2, "Alice");
ps.execute ();
ts.close();
ts = conn.prepareStatement("truncate table customers");
ts.executeUpdate();
if(ps!=null)
ps.close(); // 关闭 Statement