📄 batchupdate.java
字号:
//声明本类包含在包examples.jdbc.oracle中
package examples.jdbc.oracle;
import java.sql.*;
/**
* 这个例子演示在Oracle数据库中JDBC 2.0批处理语句的使用。
*/
public class batchUpdate {
public static void main(String argv[])
{
//声明连接,SQL语句和结果集变量
java.sql.Connection conn = null;
java.sql.Statement stmt = null;
java.sql.ResultSet rs = null;
try {
// 加载驱动获取连接
Class.forName("weblogic.jdbc.oci.Driver").newInstance();
conn = DriverManager.getConnection
("jdbc:weblogic:oracle:myServer", "USERNAME", "PASSWORD");
// 创建一个表batchTest
try {
// 如果不存在,创建它
stmt = conn.createStatement();
System.out.println("\nCreating table ...");
stmt.execute
("create table batchTest (id VARCHAR(10), col2 NUMBER, col3 NUMBER)");
}
catch (Exception e) {
//异常处理,如果表已存在,先删除它,在创建
System.out.println("Exception: " + e);
System.out.println("Table already exists. Dropping it and re-creating...");
stmt.execute("drop table batchTest");
stmt.execute
("create table batchTest (id VARCHAR(10), col2 NUMBER, col3 NUMBER)");
}
System.out.println("Table created.");
// 创建语句对象
// 增加批处理语句
stmt.addBatch("INSERT INTO batchTest VALUES ('JOE', 20,35)");
stmt.addBatch("INSERT INTO batchTest VALUES ('Bob', 30,44)");
stmt.addBatch("INSERT INTO batchTest VALUES ('Ed', 34,22)");
try {
//执行批处理语句
stmt.executeBatch();
} catch (Exception e) {
//异常处理
System.out.println("Exception while executing batch:\n " + e);
}
//显示更新的行
stmt.execute("SELECT * FROM batchTest");
//返回结果集
rs = stmt.getResultSet();
//打印结果集
while (rs.next() ) {
System.out.println(rs.getString("id") + " "
+ rs.getInt("col2") + " " +
rs.getInt("col3"));
}
// 删除表清除连接
System.out.println("\nDropping table...");
stmt.execute("drop table batchTest");
System.out.println("Table dropped.");
} catch (Exception e) {
System.out.println("Exception was thrown: " + e.getMessage());
} finally { //关闭连接和一切资源
try {
if (stmt != null)
stmt.close();
if (rs != null)
rs.close();
if (conn != null)
conn.close();
} catch (SQLException sqle) {
System.out.println("SQLException was thrown: " + sqle.getMessage());
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -