大数据对象处理主要有 CLOB(character large object)和 BLOB(binary large object)两种类型的字段;
在 CLOB中可以存储大字符数据对象,比如长篇小说;
在 BLOB 中可以存放二进制大数据对象,比如图片,电影,音乐;
1.处理 CLOB 数据
设置数据
eg:
public static int addTextDate()throws Exception
{
Connection con = util1.getCon(); //获取连接
String sql = "update t_book set textFile = ? where id = 1;"; //textFile是增加的一个字段,数据库中它是longtext类型地
File conText = new File("F://bo.txt"); //一个txt file文件
InputStream inputStream = new FileInputStream(conText); //获取流
PreparedStatement prep = con.prepareStatement(sql);
//下面这句话很重要,用了setAsciiStream方法来给longtext类型字段赋值
prep.setAsciiStream(1,inputStream, conText.length()); //设置第五个字段 ,这里的1,代表的是前面的第一个?
int result = prep.executeUpdate();
return result;
}
读取数据
eg:
public static void dislpayLongText()throws Exception
{
Connection con = util1.getCon(); //获取连接
String sql = "select * from t_book where id = 1;"; //sql语句
PreparedStatement prep = con.prepareStatement(sql); // 预处理sql语句
ResultSet res = prep.executeQuery(); //获取结果集
if(res.next())
{
Clob clob = res.getClob("textFile"); //获取大数据字符串
String c = clob.getSubString(1, (int)clob.length());
System.out.print(c);
}
util1.close(prep, con);
}
2.处理 BLOG 数据
设置数据:
eg:
public static int addBinaryDate()throws Exception
{
Connection con = util1.getCon(); //获取连接
String sql = "update t_book set pro = ? where id = 1"; //sql语句
PreparedStatement prep = con.prepareStatement(sql); //预处理sql语句
File pic = new File("F://b.jpg"); //图片文件
InputStream input = new FileInputStream(pic); //图片输入流
prep.setBinaryStream(1, input, pic.length()); //设置 ?值
int result = prep.executeUpdate(); //执行sql操作语句
return result;
}
读取函数,将其保存在e盘
eg:
public static void displayBinaryDate()throws Exception
{
Connection con = util1.getCon(); //获取连
String sql = "select * from t_book where id = 1;"; //SQl语句
PreparedStatement prep = con.prepareStatement(sql); //预处理sql语句
ResultSet res = prep.executeQuery(); //获取查询结果集
if(res.next())
{
Blob blob = res.getBlob("pro"); //获取二进制文件
OutputStream out = new FileOutputStream(new File("E://123.jpg")); //指定位置
out.write(blob.getBytes(1, (int)blob.length())); //写入
out.close(); //关闭输出流
util1.close(prep, con);
}
}