English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JDBC ASCII and Binary Data Streams

The PreparedStatement object can use input and output streams to provide parameter data. This allows you to place an entire file into a database column that can save large values (such as CLOB and BLOB data types).

There are methods available that can be used for streaming data-

  • setAsciiStream(): This method is used to provide larger ASCII values.

  • setCharacterStream(): This method is used to provide larger UNICODE values.

  • setBinaryStream(): This method is used to provide larger binary values.

The setXXXStream () method requires an additional parameter in addition to the parameter placeholder, which is the file size. This parameter informs the driver how much data should be sent to the database.

Online example

For example, if we want to upload the XML file XML_Data.xml to the database table. This is the content of this XML file-

<?xml version="1.0"?>
<Employee>
<id>100</id>
<first>Zara</first>
<last>Ali</last>
<Salary>10000</Salary>
<Dob>18-08-1978</Dob>
<Employee>

Place this XML file in the directory where this example will be run.

This example will create a database table XML_Data, and then upload the file XML_Data.xml to the table.

Copy and paste the following example into JDBCExample.java, as follows compile and run:

// Import the required software packages
import java.sql.*;
import java.io.*;
import java.util.*;
public class JDBCExample {
   // 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 = "username";
   static final String PASS = "password";
   
   public static void main(String[] args) {
   Connection conn = null;
   PreparedStatement pstmt = null;
   Statement stmt = null;
   ResultSet rs = null;
   try{
      // Register the JDBC driver program
      Class.forName("com.mysql.jdbc.Driver");
      // Open the connection
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);
      //Create a Statement object and build the 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,100);
      pstmt.setAsciiStream(2,fis,(int)fileLength);
      pstmt.execute();
      //Close the input stream
      fis.close();
      // Perform a query to get the row
      SQL = "SELECT Data FROM XML_Data WHERE id=10"0";
      rs = stmt.executeQuery(SQL);
      // Get the first line
      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 the result
         System.out.println(bos.toString());
      }
      // Clean up the environment
      rs.close();
      stmt.close();
      pstmt.close();
      conn.close();
   }catch(SQLException se){
      //Handle JDBC error
      se.printStackTrace();
   }catch(Exception e){
      //Handle Class.forName error
      e.printStackTrace();
   }finally{
      //Used to close resources
      try{
         if(stmt!=null)
            stmt.close();
      }catch(SQLException se2){
      }// We are helpless
      try{
         if(pstmt!=null)
            pstmt.close();
      }catch(SQLException se2){
      }// We are helpless
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
         se.printStackTrace();
      }
   }//End of try
   System.out.println("Goodbye!");
}//End of 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)";
   //If it exists, please delete the table first.
   try{
      stmt.executeUpdate("DROP TABLE XML_Data");
   }catch(SQLException se){
   }// Nothing done
   //Establishing table.
   stmt.executeUpdate(streamingDataSql);
}//End createXMLTable
}//End JDBCExample

Now let's compile the above example as follows:

C:\>javac JDBCExample.java
C:\>

RuntimeJDBCExampleIt will produce the following result-

C:\>java JDBCExample
Connecting to database...
Creating XML_Data table...
<?xml version="1.0"?>
<Employee>
<id>100</id>
<first>Zara</first>
<last>Ali</last>
<Salary>10000</Salary>
<Dob>18-08-1978</Dob>
<Employee>
Goodbye!
C:\>