Example: Inserting or updating data

To insert into or update BYTE and TEXT columns, read a stream of data from a source, such as an operating system file, and transmit it to the database as a java.io.InputStream object. The PreparedStatement interface provides methods for setting an input parameter to this Java™ input stream. When the statement is executed, HCL OneDB™ JDBC Driver makes repeated calls to the input stream, reading its contents and transmitting those contents as the actual parameter data to the database.

For BYTE data types, use the PreparedStatement.setBinaryStream() method to set the input parameter to the InputStream object. For TEXT data types, use the PreparedStatement.setAsciiStream() method.

The following example from the ByteType.java program shows how to insert the contents of the operating system file data.dat into a column of data type BYTE:
try
{
        stmt = conn.createStatement();
        stmt.executeUpdate("create table tab1(col1 byte)");
}
catch (SQLException e)
{
        System.out.println("Failed to create table ..." + e.getMessage());
}

try
{
        pstmt = conn.prepareStatement("insert into tab1 values (?)");
}
catch (SQLException e)
{
        System.out.println("Failed to Insert into tab: " + e.toString());
}

File file = new File("data.dat");
int fileLength = (int) file.length();
InputStream value = null;
FileInputStream fileinp = null;
int row = 0;
String str = null;
int        rc = 0;
ResultSet rs = null;

System.out.println("Inserting data ...\n");

try
{
        fileinp =  new FileInputStream(file);
        value = (InputStream)fileinp;
}
catch (Exception e) {}

try
{
        pstmt.setBinaryStream(1,value,10); //set 1st column
}
catch (SQLException e)
{
        System.out.println("Unable to set parameter");
}

set_execute();



...
public static void set_execute()
{
try
{
        pstmt.executeUpdate();
}
catch (SQLException e)
{
   System.out.println("Failed to Insert into tab: " + e.toString());
   e.printStackTrace();
}
}

The example first creates a java.io.File object that represents the operating system file data.dat. The example then creates a FileInputStream object to read from the object of type File. The object of type FileInputStream is cast to its superclass InputStream, which is the expected data type of the second parameter to the PreparedStatement.setBinaryStream() method. The setBinaryStream() method executes on the already prepared INSERT statement, which sets the input stream parameter. Finally, the PreparedStatement.executeUpdate() method executes, which inserts the contents of the data.dat operating system file into the column of type BYTE.

The TextType.java program shows how to insert data into a column of type TEXT. It is similar to inserting into a column of type BYTE, except the method setAsciiStream() is used to set the input parameter instead of setBinaryStream().