BLOB: Binary Large Object(BLOB in MySQL)
Example code:
@Test
public void writingCLOB_BLOG() {
Connection conn = null;
PreparedStatement ps = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://192.168.56.101:3306/javaweb", "root", "root");
ps = conn.prepareStatement("INSERT INTO `javaweb`.`users` "
+ "(`username`, `password`, `email`, `grade`, `usertext`, `headimg`) "
+ "VALUES (?,?,?,?,?,?);");
ps.setString(1, "abcd5");
ps.setString(2, "abc");
ps.setClob(
3,
new BufferedReader(new InputStreamReader(
new ByteArrayInputStream("aaaaaaaaa@gvace.com"
.getBytes())))); //put a string as stream, into clob
ps.setInt(4, 1);
ps.setClob(5, new FileReader("/home/yushan/a.log")); //a file as stream, into clob
ps.setBlob(6, new FileInputStream("/home/yushan/Pictures/db_clob_blob.png")); //a file as stream, into blob
ps.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
finally{
//Close all resources
}
}
@Test
public void readingCLOB_BLOG() {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Reader r = null;
InputStream is = null;
OutputStream os = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://192.168.56.101:3306/javaweb", "root", "root");
ps = conn.prepareStatement("SELECT * FROM `javaweb`.`users` "
+ "WHERE id=?;");
ps.setInt(1, 34);
rs = ps.executeQuery();
while(rs.next()){
Clob c = rs.getClob("usertext");
r = c.getCharacterStream();
char[] buf = new char[1024];
int len = -1;
while((len =r.read(buf))>0){
System.out.print(new String(buf));
}
Blob b = rs.getBlob("headimg");
is = b.getBinaryStream();
os = new FileOutputStream("/home/yushan/Pictures/db_clob_blob_copy.png");
len = -1;
byte[] buf1 = new byte[1024];
while((len = is.read(buf1))>0){
//System.out.print(new String(buf1));
os.write(buf1);
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
//Close all resources
}
}

No comments:
Post a Comment