为了在Oracle数据库中保存映像,通常使用Blob类型。因此,请确保您创建的表的blob数据类型为:
Name Null? Type
----------------------------------------- -------- ----------------------------
NAME VARCHAR2(255)
IMAGE BLOB
要将映像插入Oracle数据库,请执行以下步骤:
您可以使用DriverManager类的getConnection()方法连接到数据库。
通过将以下URL作为参数传递给Oracle URL,该URL为jdbc:oracle:thin:@localhost:1521 / xe(对于快速版),用户名和密码getConnection()
。
String oracleUrl = "jdbc:oracle:thin:@localhost:1521/xe";
Connection con = DriverManager.getConnection(oracleUrl, "user_name", "password");
使用Connection接口的prepareStatement()方法创建PreparedStatement对象。为此方法传递插入查询(带有占位符)作为参数。
PreparedStatement pstmt = con.prepareStatement("INSERT INTO MyTable VALUES(?, ?)");
使用PreparedStatement接口的setter方法将值设置为占位符。根据列的数据类型选择方法。例如,如果该列为VARCHAR类型,则使用setString()
method;如果该列为INT类型,则可以使用setInt()
method。
如果它是Blob类型,则可以使用setBinaryStream()
或setBlob()
方法为其设置值。向这些方法传递表示参数索引的整数变量和InputStream类的对象作为参数。
pstmt.setString(1, "sample image");
//插入Blob类型
InputStream in = new FileInputStream("E:\\images\\cat.jpg");
pstmt.setBlob(2, in);
使用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{
//注册驱动程序
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver ());
//获得连接
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");
//插入Blob类型
InputStream in = new FileInputStream("E:\\images\\cat.jpg");
pstmt.setBlob(2, in);
//执行语句
pstmt.execute();
System.out.println("Record inserted");
}
}
Connected to Oracle database.....
Record inserted.....