JDBC ASCII流 和 二进制数据

jdbc ascii流 和 二进制数据

preparedstatement 对象可以使用输入和输出流来提供参数数据。能够将整个文件放入可以容纳大值的数据库列,例如 clob 和 blob 数据类型。

有以下方法可用于流式传输数据:

  • setasciistream() :此方法用于提供大的ascii值。
  • setcharacterstream() :此方法用于提供较大的unicode值。
  • setbinarystream() :此方法用于提供较大的二进制值。

setxxxstream() 方法除了参数占位符之外还需要额外的参数和文件大小。此参数通知驱动程序使用流向数据库发送多少数据。

 

1. ascii流 使用范例

考虑要将xml文件 xml_data.xml 上传到数据库表中。下面是xml文件的内容 -

<?xml version="1.0"?>
<employee>
    <id>125</id>
    <first>max</first>
    <last>su</last>
    <salary>18000</salary>
    <dob>18-08-1978</dob>
<employee>

将此xml文件保存在要运行此示例的同一目录中。

此示例将在数据库创建一个表:xml_data,然后将文件 xml_data.xml 上传到此表中。

复制以下示例代码,并保存在文件:streamingdata.java 中,编译并运行如下 -

// import required packages
import java.sql.*;
import java.io.*;
import java.util.*;

public class streamingdata {
   // jdbc driver name and database url
   static final string jdbc_driver = "com.mysql.jdbc.driver";  
   static final string db_url = "jdbc:mysql://localhost/emp";

   //  database credentials
   static final string user = "root";
   static final string pass = "123456";

   public static void main(string[] args) {
   connection conn = null;
   preparedstatement pstmt = null;
   statement stmt = null;
   resultset rs = null;
   try{
      // register jdbc driver
      class.forname("com.mysql.jdbc.driver");

      // open a connection
      system.out.println("connecting to database...");
      conn = drivermanager.getconnection(db_url,user,pass);

      //create a statement object and build table
      stmt = conn.createstatement();
      createxmltable(stmt);

      //open a fileinputstream
      file f = new file("xml_data.xml");
      long filelength = f.length();
      fileinputstream fis = new fileinputstream(f);

      //create preparedstatement and stream data
      string sql = "insert into xml_data values (?,?)";
      pstmt = conn.preparestatement(sql);
      pstmt.setint(1,125);
      pstmt.setasciistream(2,fis,(int)filelength);
      pstmt.execute();

      //close input stream
      fis.close();

      // do a query to get the row
      sql = "select data from xml_data where id=125";
      rs = stmt.executequery (sql);
      // get the first row
      if (rs.next ()){
         //retrieve data from input stream
         inputstream xmlinputstream = rs.getasciistream (1);
         int c;
         bytearrayoutputstream bos = new bytearrayoutputstream();
         while (( c = xmlinputstream.read ()) != -1)
            bos.write(c);
         //print results
         system.out.println(bos.tostring());
      }
      // clean-up environment
      rs.close();
      stmt.close();
      pstmt.close();
      conn.close();
   }catch(sqlexception se){
      //handle errors for jdbc
      se.printstacktrace();
   }catch(exception e){
      //handle errors for class.forname
      e.printstacktrace();
   }finally{
      //finally block used to close resources
      try{
         if(stmt!=null)
            stmt.close();
      }catch(sqlexception se2){
      }// nothing we can do
      try{
         if(pstmt!=null)
            pstmt.close();
      }catch(sqlexception se2){
      }// nothing we can do
      try{
         if(conn!=null)
            conn.close();
      }catch(sqlexception se){
         se.printstacktrace();
      }//end finally try
   }//end try
   system.out.println("goodbye!");
}//end main

public static void createxmltable(statement stmt) 
   throws sqlexception{
   system.out.println("creating xml_data table..." );
   //create sql statement
   string streamingdatasql = "create table xml_data " +
                             "(id integer, data long)";
   //drop table first if it exists.
   try{
      stmt.executeupdate("drop table xml_data");
   }catch(sqlexception se){
   }// do nothing
   //build table.
   stmt.executeupdate(streamingdatasql);
}//end createxmltable
}//end jdbcexample

 

2. 编译运行

编译上面代码,如下:

f:\worksp\jdbc>javac -djava.ext.dirs=f:\worksp\jdbc\libs streamingdata.java
 

执行上面编译后的代码,得到以下结果:

f:\worksp\jdbc>java -djava.ext.dirs=f:\worksp\jdbc\libs streamingdata

connecting to database...
thu jun 01 21:42:00 cst 2017 warn: establishing ssl connection without server's identity verification is not recommended. according to mysql 5.5.45+, 5.6.26+ and 5.7.6+ requirements ssl connection must be established by default if explicit option isn't set. for compliance with existing applications not using ssl the verifyservercertificate property is set to 'false'. you need either to explicitly disable ssl by setting usessl=false, or set usessl=true and provide truststore for server certificate verification.
creating xml_data table...
<?xml version="1.0"?>
<employee>
        <id>125</id>
        <first>max</first>
        <last>su</last>
        <salary>18000</salary>
        <dob>18-08-1978</dob>
<employee>
goodbye!

f:\worksp\jdbc>

下一节:jdbc 创建数据库范例

jdbc 教程

相关文章