📄 longvarchar.java
字号:
//声明本类包含在包examples.jdbc.oracle中
package examples.jdbc.oracle;
//声明本类要引入的其他包和类
import java.io.*;
import java.sql.*;
import java.util.Properties;
/**
* 这个实例是个独立的应用程序演示了一个从Oracle列中插入和提取数据的方法。
*/
public class longvarchar {
/**
* 从命令行运行这个程序,这个程序包含4个参数
* 4个参数
* 数据库连接的用户名
* 用户的密码
* 数据库管理系统服务器的TNS别名
* 插入到DBMS的文件名
* 返回的文件具有相同的名字并带有.out扩展名
* @参数 args Username, password, DBMS, 和 filename
*/
public static void main(String[] args) {
//声明数据库连接、语句对象变量、PreparedStatement变量、结果集变量文件输入输出流变量
Connection conn = null;
Statement stmt = null;
PreparedStatement ps = null;
ResultSet rs = null;
FileInputStream fis = null;
FileOutputStream fos = null;
if (args.length < 4) {
//打印用法提示
System.out.println("用法: java examples.jdbc.oracle.longvarchar " +
"USER PASSWORD SERVER SRCFILE");
return;
}
try {
// 设置连接属性
Properties props = new Properties();
props.put("user", args[0]);
props.put("password", args[1]);
props.put("server", args[2]);
//加在驱动程序
Driver myDriver = (Driver) Class.forName("weblogic.jdbc.oci.Driver").newInstance();
//建立连接
conn = myDriver.connect("jdbc:weblogic:oracle", props);
// 创建SQl语句对象
stmt = conn.createStatement();
try {
//执行SQL语句,删除表WLLongVarChar
stmt.executeUpdate("drop table WLLongVarChar");
}
catch (SQLException sqe) {
//异常处理
if (sqe.getErrorCode() != 942)
sqe.printStackTrace();
}
// 创建这个实例要用到的表WLLongVarChar
stmt.executeUpdate("create table WLLongVarChar (col1 long raw)");
//关闭语句对象
stmt.close();
// 打开文件并把文件流附加到一个PreparedStatement对象
fis = new FileInputStream(args[3]);
//插入操作
ps = conn.prepareStatement("insert into WLLongVarChar values(?)");
//设置字节流参数
ps.setBinaryStream(1, fis, fis.available());
// 执行PreparedStatement把文件内容存到数据库中
ps.executeUpdate();
ps.close();
fis.close();
stmt = conn.createStatement();
//查询表所有内容并返回到结果集对象
rs = stmt.executeQuery("select * from WLLongVarChar");
while (rs.next()) {
// 这里,我们把long raw列内容写入到一个新的文件,扩展名为".out" 。
// 创建文件输出流
fos = new FileOutputStream(args[3] + ".out");
// 创建输入流
BufferedInputStream bis = new BufferedInputStream(rs.getBinaryStream(1));
BufferedOutputStream bos = new BufferedOutputStream(fos);
int x;
//同时读、写操作
while ((x = bis.read()) != -1)
bos.write((byte) x);
//清空输出流
bos.flush();
//关闭输出流和输入流
fos.close();
bis.close();
System.out.println("The output is in the file " + args[3] + ".out");
}
//关闭结果集
rs.close();
}
catch (Exception e) {
//异常处理
e.printStackTrace();
}
finally {
// 关闭资源
try {
if (stmt != null) {
try {
//删除表WLLongVarChar
stmt.executeUpdate("drop table WLLongVarChar");
stmt.close();
}
catch (Exception e) {}
}
conn.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -