JDBC可滚动可更新感知更新结果集
2009-12-19 00:00:00 来源:WEB开发网注意,要确保二进制数据长度足够大,否则可能导致数据写入不完整的问题。
三、插入读取clob字段
clob在MySQL5中对应的就是text字段,可以根据实际需要选择合适的长度。
package lavasoft.jdbctest;
import lavasoft.common.DBToolkit;
import java.io.*;
import java.sql.*;
/**
* 操作MySQL5的Clob字段
*
* @author leizhimin 2009-12-3 13:56:16
*/
public class ClobTest {
public static void main(String[] args) {
insertClob();
queryClob();
}
public static void insertClob() {
Connection conn = DBToolkit.getConnection();
PreparedStatement ps = null;
try {
String sql = "insert into testdb.user (name, pswd, remark) values (?, ?, ?)";
ps = conn.prepareStatement(sql);
ps.setString(1, "zhangsan");
ps.setString(2, "111");
//设置二进制参数
File file = new File("D:\\new\\dbtools\\src\\res\\PIC.PNG");
// InputStreamReader reader = new InputStreamReader(new FileInputStream("D:\\new\\dbtools\\src\\res\\TEXT.txt"),"GB18030");
InputStreamReader reader = new InputStreamReader(new FileInputStream("D:\\new\\dbtools\\src\\res\\TEXT.txt"));
ps.setCharacterStream(3, reader, (int) file.length());
ps.executeUpdate();
reader.close();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBToolkit.closeConnection(conn);
}
}
public static void queryClob() {
Connection conn = DBToolkit.getConnection();
PreparedStatement ps = null;
Statement stmt = null;
ResultSet rs = null;
try {
String sql = "select remark from user where id = 1";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
if (rs.next()) {
Reader reader = rs.getCharacterStream(1);
File file = new File("D:\\new\\dbtools\\src\\res\\TEXT_COPY.txt");
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file));
// OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file),"ISO-8859-1");
// OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file),"GB18030");
char[] buff = new char[1024];
for (int i = 0; (i = reader.read(buff)) > 0;) {
writer.write(buff, 0, i);
}
writer.flush();
writer.close();
reader.close();
}
rs.close();
stmt.close();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBToolkit.closeConnection(conn);
}
}
}
在处理blob字段时候,由于直接处理的是二进制流,所以没啥问题。在处理clob字段的时候,由于数据库对clob是以字符的形式进行存储,这就有一个编码问题。本文虽然成功的插入读取了clob字段,但是还没有解决乱码问题,因为JDBC在获取到clob的时候,已经对其进行了编码,Reader reader = rs.getCharacterStream(1); 这就导致了编码的混乱,如果要彻底解决,还需要看看MySQL驱动的实现。通过非常规手段来解决。为了绕开此问题,可以将clob的数据存储为blog来操作,可以避免此问题。
出处:http://lavasoft.blog.51cto.com/62575/238222
更多精彩
赞助商链接