JDBC笔记-BLOB和获取主键
2016-05-02 19:59
183 查看
BLOB是MySQL中的数据类型,在Oracle中类型稍有不同,但是原理一致。
MySQL的四种BLOB类型(单位:字节)
TinyBlob 最大 255,Blob 最大 65K,MediumBlob 最大16M,LongBlob 最大 4G
由于BLOB的数据时无法用字符串拼装的,所以插入BLOB类型的数据必须使用PreparedStatement。
本文中举例说明通过JDBC来操作BLOB的方法。
在插入数据时,获取当前插入数据对应的主键举例
public static void update() throws Exception{
Connection conn = DBTools.getConnection();
String sql = "insert into student (name) values('username')";
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
while(rs.next())
{
System.out.println("PrimaryKey:" + rs.getObject(1));
}
}
<完>
MySQL的四种BLOB类型(单位:字节)
TinyBlob 最大 255,Blob 最大 65K,MediumBlob 最大16M,LongBlob 最大 4G
由于BLOB的数据时无法用字符串拼装的,所以插入BLOB类型的数据必须使用PreparedStatement。
本文中举例说明通过JDBC来操作BLOB的方法。
插入BLOB数据
如下所示,其中DBTools是自己完成的静态库,用于操作数据库。public static void blobInsertTest() throws Exception{ InputStream is = new FileInputStream("E:\\test.jpg"); Connection conn = DBTools.getConnection(); String sql = "insert into student (photo) value (?)"; PreparedStatement ps = conn.prepareStatement(sql); ps.setBlob(1, is); ps.executeUpdate(); is.close(); DBTools.release(null, ps, conn); }
取出BLOB数据
取出BLOB图片,将其另存到磁盘中。public static void blobSelectTest() throws Exception{ Connection conn = DBTools.getConnection(); String sql = "select photo from student where id = 12"; PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); while(rs.next()){ Blob blob = rs.getBlob("photo"); InputStream is = blob.getBinaryStream(); FileOutputStream fos = new FileOutputStream("E:\\test2.jpg"); byte[] photoData = new byte[1024]; while(is.read(photoData) != -1){ fos.write(photoData); } is.close(); fos.close(); } DBTools.release(rs, ps, conn); }
在插入数据时,获取当前插入数据对应的主键举例
public static void update() throws Exception{
Connection conn = DBTools.getConnection();
String sql = "insert into student (name) values('username')";
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
while(rs.next())
{
System.out.println("PrimaryKey:" + rs.getObject(1));
}
}
<完>
相关文章推荐
- leetcode笔记—Find the Duplicate Number
- HDOJ-2066-一个人的旅行
- redis-集合
- 经典SQL练习题3----student/score/cource/teacher
- HDU 5677 ztr loves substring
- Codeforces Round #228 (Div. 1) A. Fox and Box Accumulation (贪心)
- Spring之集合DI
- 学习笔记之深入浅出MFC 第8章 C++重要特性----静态变量(static)
- Android 的三种依赖注入库
- POJ 1753 搜索
- java基础————安卓开发新手的前提
- maven遇到的问题解决方法 -8080端口被占用
- 常用正则表达式
- 字符数组(一)
- poj 1265&&poj 2954(Pick定理)
- poj 2226 Muddy Fields
- 部分mysql学习
- POJ11422 Air Raid
- QT学习记录
- 经典SQL练习题2----emp/dept