Java和MySQL数据库大文本和二进制操作

MySQL中VARCHAR上限为65535个字节, 如果超出这个范围. 需要设置为TEXT.

LONGTEXT最大可以4G

存储TEXT

//定义sql语句

String sql="insert into clob(file) value(?)";

PreparedStatement ps =conn.prepareStatement(sql);

File file = new File("res/ClobDemo.Java");

Reader reader = new FileReader(file);

ps.setCharacterStream(1, reader,(int) file.length());

ps.executeUpdate();

//最后要关闭流

reader.close();

读取TEXTString sql="select file from clob";

PreparedStatement ps =conn.prepareStatement(sql);

ResultSet rs =ps.executeQuery();

if (rs.next()) {

       Reader reader = rs.getCharacterStream(int columnIndex);

       // 这个Reader就是从数据库中读取数据的流, 操作这个流来读取数据

BufferedReader br = new BufferedReader(r);

BufferedWriter bw = new BufferedWriter(new FileWriter(

"res/new.txt"));

 String s = "";

 while ((s = br.readLine()) != null) {

 bw.write(s + "\n");

 }

              bw.flush();

              br.close();

              r.close();

              bw.close();

}

2.   BLOB

BLOB用来存储大段的二进制数据, 例如图片, 音频, 视频. LONGBLOB最大4G

 存储BLOB

PreparedStatement ps =conn.prepareStatement("insert intobig_binary(file) values(?)");

File file = new File("src/cn/itcast/jdbc1/clob_blob/IMG_0007.jpg");

InputStream in = newFileInputStream(file);

ps.setBinaryStream(1, in, (int) file.length());

ps.executeUpdate();

 读取BLOB

PreparedStatement ps =conn.prepareStatement("select filefrom big_binary");

ResultSet rs =ps.executeQuery();

if (rs.next()) {

    InputStream in = rs.getBinaryStream(1);

    // 这个InputStream就是从数据库中读取数据的流, 操作这个流来读取数据

File file = new File("res/newgirl.jpg");
FileOutputStream fos = new FileOutputStream(file);
int num = in.available();
byte buffer[] = new byte[num];
while(in.read(buffer,0,num) != -1){
fos.write(buffer);
}
System.out.println("左边");
in.close();
fos.close();

}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyxzsx.html