在实际开发中,程序需要把大文件或二进制数据保存到数据库。
基本概念:大数据也称之位LOB,又分为clob存储大文本、blob存储二进制如音频、视频。MySQL只有blob,没有clob,mysql存储大文本采用的是Text。
MySql中Text类型方法调用:
设置:PreparedStatement.setCharacterStream(index, reader, length);
注意length长度须设置,并且设置为int型
获取:reader = resultSet. getCharacterStream(i);
reader = resultSet.getClob(i).getCharacterStream();
string s = resultSet.getString(i);
MySql中BLOB类型方法调用:
设置:PreparedStatement. setBinaryStream(i, inputStream, length);
获取:InputStream in = resultSet.getBinaryStream(i);
InputStream in = resultSet.getBlob(i).getBinaryStream();
JDBC批处理:当需要向数据库发送一批SQL语句执行时,应避免向数据库一条条的发送执行,而应采用JDBC的批处理机制,以提升执行效率。
实现批处理方法:
1、 Statement.addBatch(sql)
优点:可以向数据库发送多条不同的SQL语句。
缺点:SQL语句没有预编译。
当向数据库发送多条语句相同,但仅参数不同的SQL语句时,需重复写上很多条SQL语句
执行批处理SQL语句:
executeBatch()方法:执行批处理命令
clearBatch()方法:清除批处理命令
2、PreparedStatement.addBatch()
优点:发送的是预编译后的SQL语句,执行效率高。
缺点:只能应用在SQL语句相同,但参数不同的批处理中。因此此种形式的批处理经常用于在同一个表中批量插入数据,或批量更新表的数据。
获得数据库自动生成的主键
示例:Connection conn = JdbcUtil.getConnection();
String sql = "insert into user(name,password,email,birthday)
values('abc','123','abc@sina.com','1978-08-08')";
PreparedStatement st = conn.
prepareStatement(sql,Statement.RETURN_GENERATED_KEYS );
st.executeUpdate();
ResultSet rs = st.getGeneratedKeys(); //得到插入行的主键
if(rs.next())
System.out.println(rs.getObject(1));