如何使用JDBC從表中檢索二進位制資料?
SQL資料庫提供了一種名為Blob(Binary Large Object)的資料型別,您可以在其中儲存大型二進位制資料,例如影像。
為了從表中檢索二進位制(流)值,JDBC在**PreparedStatement**介面中提供了一個名為**getBinaryStream()**的方法。
它接受一個整數,表示表的列索引,並從中檢索二進位制資料。
您可以使用此方法從表中檢索二進位制資料,如下所示:
FileInputStream fin = new FileInputStream("javafx_logo.jpg");
pstmt.setBinaryStream(3, fin);示例
讓我們使用下面的CREATE語句在MySQL中建立一個名為**tutorials_data**的表:
CREATE TABLE tutorials_data( Name VARCHAR(255), Type VARCHAR(50), Logo BLOB );
下面的JDBC程式建立與MySQL的連線,並將3條記錄插入到**tutorials_data**表中。
作為第三列LOGO的值,此程式儲存二進位制資料(來自本地目錄的影像),並檢索該表的所有記錄。
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class BinaryDataToTable {
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:///sampledatabase";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Inserting values
String query = "INSERT INTO tutorials_dataa(Name, Type, Logo) VALUES (?, ?, ?)";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, "JavaFX");
pstmt.setString(2, "Java_library");
FileInputStream fin = new FileInputStream("javafx_logo.jpg");
pstmt.setBinaryStream(3, fin);
pstmt.execute();
pstmt.setString(1, "CoffeeScript");
pstmt.setString(2, "scripting Language");
fin = new FileInputStream("coffeescript_logo.jpg");
pstmt.setBinaryStream(3, fin);
pstmt.execute();
pstmt.setString(1, "Cassandra");
pstmt.setString(2, "NoSQL database");
fin = new FileInputStream("cassandra_logo.jpg");
pstmt.setBinaryStream(3, fin);
pstmt.execute();
System.out.println("Records inserted......");
}
}輸出
Connection established...... Data inserted Name: JavaFX, Tutorial Type: Java_library, Logo: java.io.ByteArrayInputStream@7bfcd12c Name: CoffeeScript, Tutorial Type: scripting Language, Logo: java.io.ByteArrayInputStream@42f30e0a Name: Cassandra, Tutorial Type: NoSQL database, Logo: java.io.ByteArrayInputStream@24273305
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP