在 SQLite Ruby 教程的这一章中,我们将使用图像文件。 请注意,有些人反对将图像放入数据库。 在这里,我们只展示如何做。 我们不讨论是否将图像保存在数据库中的技术问题。
sqlite> CREATE TABLE Images(Id INTEGER PRIMARY KEY, Data BLOB);
对于此示例,我们创建一个名为Images的新表。 对于图像,我们使用BLOB数据类型,代表二进制大对象。
插入图像
在第一个示例中,我们将图像插入 SQLite 数据库。
#!/usr/bin/rubyrequire 'sqlite3'beginfin = File.open "woman.jpg" , "rb"img = fin.readrescue SystemCallError => eputs eensurefin.close if finendbegindb = SQLite3::Database.open 'test.db'blob = SQLite3::Blob.new imgdb.execute "INSERT INTO Images VALUES(1, ?)", blobrescue SQLite3::Exception => eputs "Exception occurred"puts eensuredb.close if dbend
我们从当前工作目录中读取图像,并将其写入 SQLite test.db数据库的Images表中。
fin = File.open "woman.jpg" , "rb"img = fin.read
我们打开并阅读 JPG 图像。 read方法以字符串形式返回数据。
blob = SQLite3::Blob.new img
我们创建SQLite3::Blob类的实例。 它用于处理二进制数据。
db.execute "INSERT INTO Images VALUES(1, ?)", blob
图像被写入数据库。
读取图像
在本节中,我们将执行相反的操作。 我们将从数据库表中读取图像。
#!/usr/bin/rubyrequire 'sqlite3'begindb = SQLite3::Database.open 'test.db'data = db.get_first_value "SELECT Data FROM Images LIMIT 1"f = File.new "woman2.jpg", "wb"f.write datarescue SQLite3::Exception, SystemCallError => eputs "Exception occurred"puts eensuref.close if fdb.close if dbend
我们从图像表中读取图像数据,并将其写入另一个文件,我们将其称为woman2.jpg。
data = db.get_first_value "SELECT Data FROM Images LIMIT 1"
该行从表中选择图像数据。
f = File.new "woman2.jpg", "wb"f.write data
我们打开一个新的图像文件,并将检索到的数据写入该文件。 然后我们关闭文件。
SQLite Ruby 教程的这一部分专门用于读取和写入图像。
