How to load a file into database column?


While some other database systems might have an SQL function for this, with Firebird you need an application. Datatype that holds binary files is called BLOB, and you should use sub_type zero, as sub_type one is for text-only data. Let's create a table to hold the file. We'll have a filename column and a blob column containing the file itself:

CREATE TABLE t1
(
file_name VARCHAR(200),
file_data BLOB SUB_TYPE 0
);

The blobs are loaded via parametrized query:

INSERT INTO t1 (file_name, file_data) VALUES (?, ?);

Now use your favorite programming language to set the parameters. Here's a short C++ example using IBPP library:

// previously setup variables
IBPP::Database db;
IBPP::Transaction tr;
IBPP::Statement st;
std::string file_content; // loaded from file: myfile.pdf

// writing file data to Blob column
st->Prepare("INSERT INTO t1 (file_name, file_data) VALUES (?, ?)");
st->Set(1, "myfile.pdf");
IBPP::Blob b = IBPP::BlobFactory(db, tr);
b->Save(file_content);
st->Set(2, b);
st->Execute();


Here's an example how to update a BLOB field using PHP:

ibase_connect($database, $user, $password) or die(ibase_errmsg());
$fd = fopen('myfile2.pdf', 'r');
$blob = ibase_blob_import($fd);
fclose($fd);
ibase_query("update table1 set blob_field = ?", $blob)
or die(ibase_errmsg());


Do you find this FAQ incorrect or incomplete? Please e-mail us what needs to be changed. To ensure quality, each change is checked by our editors (and often tested on live Firebird databases), before it enters the main FAQ database. If you desire so, the changes will be credited to your name. To learn more, visit our add content page.



All contents are copyright © 2007-2024 FirebirdFAQ.org unless otherwise stated in the text.


Links   Firebird   News   FlameRobin   Powered by FB: Home Inventory   Euchre  
Add content   About  

Categories
 Newbies
 SQL
 Installation and setup
 Backup and restore
 Performance
 Security
 Connectivity and API
 HOWTOs
 Errors and error codes
 Miscellaneous