如何从sqlite存储和检索一个blob
我已经在c + +,python和现在(也许)在C#中使用sqlite。 在所有这些我不知道如何将一个blob插入到表中。 如何在sqlite中存储和检索blob?
以下是你如何在C#中完成的
class Program { static void Main(string[] args) { if (File.Exists("test.db3")) { File.Delete("test.db3"); } using (var connection = new SQLiteConnection("Data Source=test.db3;Version=3")) using (var command = new SQLiteCommand("CREATE TABLE PHOTOS(ID INTEGER PRIMARY KEY AUTOINCREMENT, PHOTO BLOB)", connection)) { connection.Open(); command.ExecuteNonQuery(); byte[] photo = new byte[] { 1, 2, 3, 4, 5 }; command.CommandText = "INSERT INTO PHOTOS (PHOTO) VALUES (@photo)"; command.Parameters.Add("@photo", DbType.Binary, 20).Value = photo; command.ExecuteNonQuery(); command.CommandText = "SELECT PHOTO FROM PHOTOS WHERE ID = 1"; using (var reader = command.ExecuteReader()) { while (reader.Read()) { byte[] buffer = GetBytes(reader); } } } } static byte[] GetBytes(SQLiteDataReader reader) { const int CHUNK_SIZE = 2 * 1024; byte[] buffer = new byte[CHUNK_SIZE]; long bytesRead; long fieldOffset = 0; using (MemoryStream stream = new MemoryStream()) { while ((bytesRead = reader.GetBytes(0, fieldOffset, buffer, 0, buffer.Length)) > 0) { stream.Write(buffer, 0, (int)bytesRead); fieldOffset += bytesRead; } return stream.ToArray(); } } }
你需要使用sqlite的准备语句接口。 基本上,这个想法是,你准备一个占位符为你的blob声明,然后使用其中一个绑定调用“绑定”您的数据…
SQLite准备的语句
我结束了这个插入blob的方法:
protected Boolean updateByteArrayInTable(String table, String value, byte[] byteArray, String expr) { try { SQLiteCommand mycommand = new SQLiteCommand(connection); mycommand.CommandText = "update " + table + " set " + value + "=@image" + " where " + expr; SQLiteParameter parameter = new SQLiteParameter("@image", System.Data.DbType.Binary); parameter.Value = byteArray; mycommand.Parameters.Add(parameter); int rowsUpdated = mycommand.ExecuteNonQuery(); return (rowsUpdated>0); } catch (Exception) { return false; } }
阅读它的代码是:
protected DataTable executeQuery(String command) { DataTable dt = new DataTable(); try { SQLiteCommand mycommand = new SQLiteCommand(connection); mycommand.CommandText = command; SQLiteDataReader reader = mycommand.ExecuteReader(); dt.Load(reader); reader.Close(); return dt; } catch (Exception) { return null; } } protected DataTable getAllWhere(String table, String sort, String expr) { String cmd = "select * from " + table; if (sort != null) cmd += " order by " + sort; if (expr != null) cmd += " where " + expr; DataTable dt = executeQuery(cmd); return dt; } public DataRow getImage(long rowId) { String where = KEY_ROWID_IMAGE + " = " + Convert.ToString(rowId); DataTable dt = getAllWhere(DATABASE_TABLE_IMAGES, null, where); DataRow dr = null; if (dt.Rows.Count > 0) // should be just 1 row dr = dt.Rows[0]; return dr; } public byte[] getImage(DataRow dr) { try { object image = dr[KEY_IMAGE]; if (!Convert.IsDBNull(image)) return (byte[])image; else return null; } catch(Exception) { return null; } } DataRow dri = getImage(rowId); byte[] image = getImage(dri);
这工作得很好(C#):
byte[] iconBytes = null; using (var dbConnection = new SQLiteConnection(DataSource)) { dbConnection.Open(); using (var transaction = dbConnection.BeginTransaction()) { using (var command = new SQLiteCommand(dbConnection)) { command.CommandText = "SELECT icon FROM my_table"; using (var reader = command.ExecuteReader()) { while (reader.Read()) { if (reader["icon"] != null && !Convert.IsDBNull(reader["icon"])) { iconBytes = (byte[]) reader["icon"]; } } } } transaction.Commit(); } }
不需要分块。 只是投到字节数组。
在C ++中(没有错误检查):
std::string blob = ...; // assume blob is in the string std::string query = "INSERT INTO foo (blob_column) VALUES (?);"; sqlite3_stmt *stmt; sqlite3_prepare_v2(db, query, query.size(), &stmt, nullptr); sqlite3_bind_blob(stmt, 1, blob.data(), blob.size(), SQLITE_TRANSIENT);
如果查询将在blob
被破坏之前执行,则可以是SQLITE_STATIC
。