数据库中的大数据字段和二进制大数据字段(图片)

package cn.hncu;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
import java.util.UUID;

import javax.imageio.stream.FileImageInputStream;

import org.junit.Test;

import cn.hncu.pubs.ConnFactory;
//演示数据库中的大数据字段 ---“写”用PreparedStatement,“读”用Statement
public class JdbcDemo2 {
//有关文本型大数据的名称: 数据库中称text,clob Java中称: AsciiStream
//文本型大数据类型: tinytext, text, mediumtext, longtext 4种,每种有支持的最大字符数。
//最大能够支持4G,具体情况以MySQL对应版本的手册说明为准
/*
CREATE TABLE note(
id INT,
note TEXT
);
*
*/
@Test
public void saveCLob() throws Exception{
Connection con = ConnFactory.getConn();
String sql = "insert into note values(?,?)";
PreparedStatement pst = con.prepareStatement(sql);
pst.setInt(1, 1);
File file = new File("./src/cn/hncu/JdbcDemo.java");
InputStream in = new FileInputStream(file);
pst.setAsciiStream(2, in);

pst.executeUpdate();
con.close();
}

@Test
public void readCLob() throws Exception{
Connection con = ConnFactory.getConn();
String sql = "select * from note where id=1";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
rs.next();
InputStream in = rs.getAsciiStream(2);

BufferedReader br = new BufferedReader( new InputStreamReader(in));
String line=null;
while( (line=br.readLine())!=null){
System.out.println(line);
}
con.close();
}

//二进制大数据字段 binary lob ---blob Java中称: BinaryStream
/*
* CREATE TABLE img(
id INT,
img BLOB
);
*
*/
@Test
public void saveImg() throws Exception{
Connection con = ConnFactory.getConn();
String sql = "insert into img values(?,?)";
PreparedStatement pst = con.prepareStatement(sql);
pst.setInt(1, 1);
File file = new File("1.jpg");
if(!file.exists()){
return;
}
InputStream in = new FileInputStream(file);
pst.setBinaryStream(2, in, in.available());
pst.executeUpdate();
con.close();
}

@Test
public void readImg() throws Exception{
Connection con = ConnFactory.getConn();
String sql = "select * from img where id=1";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
rs.next();
InputStream in = rs.getBinaryStream(2);
byte bs[] = new byte[512];
OutputStream out = new FileOutputStream("d:/a/a.jpg");
int len=0;
while( (len=in.read(bs))!=-1){
out.write(bs, 0, len);
}
out.close();
in.close();

con.close();
}


}

原文地址:https://www.cnblogs.com/1314wamm/p/6044662.html