如何使用 Java 程序将图像插入 Oracle 数据库?
在 Oracle 数据库中保存图像通常使用 blob 类型。因此,请确保您有一个使用 blob 数据类型创建的表,如下所示:
Name Null? Type ----------------------------------------- -------- ---------------------------- NAME VARCHAR2(255) IMAGE BLOB
要将图像插入 Oracle 数据库,请按照以下步骤操作:
步骤 1:连接到数据库
您可以使用 DriverManager 类的 getConnection() 方法连接到数据库
通过将 Oracle URL(即 jdbc:oracle:thin:@localhost:1521/xe(适用于 Express 版本)、用户名和密码作为参数传递给 getConnection() 方法,连接到 Oracle 数据库。
String oracleUrl = "jdbc:oracle:thin:@localhost:1521/xe"; Connection con = DriverManager.getConnection(oracleUrl, "user_name", "password");
步骤 2:创建 Prepared 语句
使用 Connection 接口的 prepareStatement() 方法创建 PreparedStatement 对象。将插入查询(带占位符)作为参数传递给此方法。
PreparedStatement pstmt = con.prepareStatement("INSERT INTO MyTable VALUES(?, ?)");
步骤 3:将值设置为占位符
使用 PreparedStatement 接口的 setter 方法将值设置为占位符。根据列的数据类型选择方法。例如,如果列是 VARCHAR 类型,则使用 setString() 方法;如果是 INT 类型,则可以使用 setInt() 方法。
如果是 Blob 类型,则可以使用 setBinaryStream() 或 setBlob() 方法为其设置值。向这些方法传递一个表示参数索引的整数变量和一个 InputStream 类的对象作为参数。
pstmt.setString(1, "sample image");
//Inserting Blob type
InputStream in = new FileInputStream("E:\images\cat.jpg");
pstmt.setBlob(2, in);
步骤 4:执行语句
使用 PreparedStatement 接口的 execute() 方法执行上面创建的 PreparedStatement 对象。
示例
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class InsertImageToOracleDB {
public static void main(String args[]) throws Exception{
//Registering the Driver
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver ());
//Getting the connection
String oracleUrl = "jdbc:oracle:thin:@localhost:1521/xe";
Connection con = DriverManager.getConnection(oracleUrl, "system", "password");
System.out.println("Connected to Oracle database.....");
PreparedStatement pstmt = con.prepareStatement("INSERT INTO MyTable VALUES(?,?)");
pstmt.setString(1, "sample image");
//Inserting Blob type
InputStream in = new FileInputStream("E:\images\cat.jpg");
pstmt.setBlob(2, in);
//Executing the statement
pstmt.execute();
System.out.println("Record inserted");
}
}
输出
Connected to Oracle database..... Record inserted.....
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

