Suppose we already have a table named MyData in the database, which is described as follows.
+---------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+--------------+------+-----+---------+-------+ | Name | varchar(255) | YES | | NULL | | | Article | longtext | YES | | NULL | | +---------+--------------+------+-----+---------+-------+
If you need to insert the value int into the clob data type using a JDBC program, you need to use a method that reads the file content and sets it as a database row. The ReadyStatement interface provides such methods.
void setCharacterStream(int parameterIndex, Reader reader) Method sets the contents of the reader object to the value of the parameter at the given index. Other variations of this method are:
void setCharacterStream(intparameterIndex, Reader reader, int length)
void setClob(intparameterIndex, Clob x) method sets the given java .sql.Clob object as the value of the parameter at the given index. Other variations of this method are:
Example
import java.io.FileReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class InsertingValueInClob { public static void main(String args[]) throws Exception { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/sampleDB"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Inserting values String query = "INSERT INTO MyData(Name, Article ) VALUES (?, ?)"; PreparedStatement pstmt = con.prepareStatement(query); pstmt.setString(1, "JavaFX"); FileReader reader = new FileReader("E:\images\javafx.txt"); pstmt.setClob(2, reader); pstmt.execute(); System.out.println("Data inserted"); } }
Output
Connection established...... Table Created...... Contents of the table are: JavaFX E:\images\MyData_clob_output1.txt
The above is the detailed content of Write a JDBC example to insert a value of Clob data type into a table?. For more information, please follow other related articles on the PHP Chinese website!