编写一个 JDBC 示例来将 Clob 数据类型的值插入表中?

假设我们在数据库中已有一个名为 MyData 的表,其描述如下。
+---------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +---------+--------------+------+-----+---------+-------+ | Name | varchar(255) | YES | | NULL | | | Article | longtext | YES | | NULL | | +---------+--------------+------+-----+---------+-------+
如果需要使用 JDBC 程序将值 int 插入到 clob 数据类型中,则需要使用读取文件内容并将其设置为数据库行的方法。 ReadyStatement 接口提供了这样的方法。
void setCharacterStream(int parameterIndex, Reader reader) 方法将 reader 对象的内容设置为给定索引处的参数的值。此方法的其他变体是:
void setCharacterStream(intparameterIndex, Reader reader, int length)
void setCharacterStream(intparameterIndex, Reader reader, long length)
void setClob(intparameterIndex, Clob x) 方法设置给定的 java .sql.Clob 对象作为给定索引处参数的值。此方法的其他变体是:
void setClob(intparameterIndex, Reader reader)
void setClob (int parameterIndex, Reader reader, long length)
您可以使用这两种方法之一将值设置为 Clob 数据类型。
示例 h3>
以下示例使用 setClob() 方法将值设置为 Clob 数据类型。
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");
}
}输出
Connection established...... Table Created...... Contents of the table are: JavaFX E:\images\MyData_clob_output1.txt
如果您尝试使用MySQL工作台查看记录中的clob值,您可以看到插入的文本数据,如下所示:
标签:
作者:知识百科网本文地址:/database/34506.html发布于
2023-08-31 03:27:25
文章转载或复制请以超链接形式并注明出处
数据库