반응형
sqlite에서 blob을 저장하고 검색하는 방법
나는 C ++, python에서 sqlite를 사용했고 지금은 C #에서 (아마도) 사용했습니다. 이 모든 것에서 나는 테이블에 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에 대한 자리 표시자가있는 문을 준비한 다음 bind 호출 중 하나를 사용하여 데이터를 "바인딩"하는 것입니다.
나는 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 ++에 대한 완전한 예제가 없기 때문에 다음은 오류 검사없이 float 데이터의 배열 / 벡터를 삽입하고 검색하는 방법입니다.
#include <sqlite3.h>
#include <iostream>
#include <vector>
int main()
{
// open sqlite3 database connection
sqlite3* db;
sqlite3_open("path/to/database.db", &db);
// insert blob
{
sqlite3_stmt* stmtInsert = nullptr;
sqlite3_prepare_v2(db, "INSERT INTO table_name (vector_blob) VALUES (?)", -1, &stmtInsert, nullptr);
std::vector<float> blobData(128); // your data
sqlite3_bind_blob(stmtInsertFace, 1, blobData.data(), static_cast<int>(blobData.size() * sizeof(float)), SQLITE_STATIC);
if (sqlite3_step(stmtInsert) == SQLITE_DONE)
std::cout << "Insert successful" << std::endl;
else
std::cout << "Insert failed" << std::endl;
sqlite3_finalize(stmtInsert);
}
// retrieve blob
{
sqlite3_stmt* stmtRetrieve = nullptr;
sqlite3_prepare_v2(db, "SELECT vector_blob FROM table_name WHERE id = ?", -1, &stmtRetrieve, nullptr);
int id = 1; // your id
sqlite3_bind_int(stmtRetrieve, 1, id);
std::vector<float> blobData;
if (sqlite3_step(stmtRetrieve) == SQLITE_ROW)
{
// retrieve blob data
const float* pdata = reinterpret_cast<const float*>(sqlite3_column_blob(stmtRetrieve, 0));
// query blob data size
blobData.resize(sqlite3_column_bytes(stmtRetrieve, 0) / static_cast<int>(sizeof(float)));
// copy to data vector
std::copy(pdata, pdata + static_cast<int>(blobData.size()), blobData.data());
}
sqlite3_finalize(stmtRetrieve);
}
sqlite3_close(db);
return 0;
}
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);
That can be SQLITE_STATIC
if the query will be executed before blob
gets destructed.
참고URL : https://stackoverflow.com/questions/625029/how-do-i-store-and-retrieve-a-blob-from-sqlite
반응형
'developer tip' 카테고리의 다른 글
gem을 설치했지만 'gemname'이 필요하지 않습니다. (0) | 2020.12.01 |
---|---|
Multicore를 어떻게 활용하고 있습니까? (0) | 2020.12.01 |
MVC의 ActionLink에서 쿼리 문자열 매개 변수를 전달하는 방법 (0) | 2020.12.01 |
Emacs에서 시맨틱 Jump to Symbol을 사용한 후 이전 줄 위치로 돌아가는 방법은 무엇입니까? (0) | 2020.12.01 |
문자열을 char * 포인터에 할당 할 수 있지만 char [] 배열에는 할당 할 수없는 이유는 무엇입니까? (0) | 2020.12.01 |