日期:2014-05-16  浏览次数:20460 次

使用JDBC处理大数据

                      

  在实际开发中,程序需要把大文本或二进制数据保存到数据库。

 

  大数据也称之为LOB(Large Objects),LOB又分为:clob和blob

。 clob用于存储大文本。Text

?       blob用于存储二进制数据,例如图像、声音、二进制文等。

 

     对MySQL而言只有blob,而没有clob,mysql存储大文本采用的是Text,Text和blob分别又分为:

?        TINYTEXT、TEXT、MEDIUMTEXT和LONGTEXT

?        TINYBLOB、BLOB、MEDIUMBLOB和LONGBLOB

 

      而对于MySQL中的Text类型,可调用如下方法设置:

          PreparedStatement.setCharacterStream(index, reader, length);

//注意length长度须设置,并且设置为int型

       

      对MySQL中的Text类型,可调用如下方法获取:

       

      reader = resultSet. getCharacterStream(i);

reader = resultSet.getClob(i).getCharacterStream();

string s = resultSet.getString(i);

         

   对于MySQL中的BLOB类型,可调用如下方法设置:

  PreparedStatement. setBinaryStream(i,inputStream, length);

 

对MySQL中的BLOB类型,可调用如下方法获取:

 

InputStreamin  = resultSet.getBinaryStream(i);//常用

InputStreamin  =resultSet.getBlob(i).getBinaryStream();

 

使用JDBC进行批处理

   

  当需要向数据库发送一批SQL语句执行时,应避免向数据库一条条的发送执行,而应采用JDBC的批处理机制,以提升执行效率。

实现批处理有两种方式,第一种方式:

?        Statement.addBatch(sql)  list

执行批处理SQL语句

?        executeBatch()方法:执行批处理命令

?        clearBatch()方法:清除批处理命令

  例如:

    Connectionconn = null;

Statement st = null;

ResultSet rs = null;

try {

conn = JdbcUtil.getConnection();

String sql1 = "insert intouser(name,password,email,birthday)

       values('kkk','123','abc@sina.com','1978-08-08')";

String sql2 = "update user setpassword='123456' where id=3";

st = conn.createStatement();

st.addBatch(sql1);  //把SQL语句加入到批命令中

st.addBatch(sql2);  //把SQL语句加入到批命令中

st.executeBatch();//执行批处理语句

} finally{

       JdbcUtil.free(conn,st, rs);

}

 

 

采用Statement.addBatch(sql)方式实现批处理:

?        优点:可以向数据库发送多条不同的SQL语句。

?        缺点:

?        SQL语句没有预编译。

?        当向数据库发送多条语句相同,但仅参数不同的SQL语句时,需重复写上很多条SQL语句。例如:

              Insertinto user(name,password) values(‘aa’,’111’);

              Insertinto user(name,password) values(‘bb’,’222’);

              Insertinto user(name,password) values(‘cc’,’333’);

              Insertinto user(name,password) values(‘dd’,’444’);

 

 

  实现批处理的第二种方式:

?        PreparedStatement.addBatch()

 &