Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从sqlite存储和检索blob? 我在C++、Python中使用SQLite,现在可能在C中使用了。在所有这些中,我不知道如何将BLB插入表中。如何在sqlite中存储和检索blob?_Sqlite_Blob - Fatal编程技术网

如何从sqlite存储和检索blob? 我在C++、Python中使用SQLite,现在可能在C中使用了。在所有这些中,我不知道如何将BLB插入表中。如何在sqlite中存储和检索blob?

如何从sqlite存储和检索blob? 我在C++、Python中使用SQLite,现在可能在C中使用了。在所有这些中,我不知道如何将BLB插入表中。如何在sqlite中存储和检索blob?,sqlite,blob,Sqlite,Blob,您需要使用sqlite的prepared statements接口。基本上,这个想法是为blob准备一个带有占位符的语句,然后使用其中一个bind调用来绑定数据 以下是如何在C中实现此功能: 班级计划 { 静态环[]args { 如果文件为.existest.db3 { 文件Deletetest.db3; } 使用var connection=new-SQLiteConnectionData-Source=test.db3;Version=3 using var command=new SQLi

您需要使用sqlite的prepared statements接口。基本上,这个想法是为blob准备一个带有占位符的语句,然后使用其中一个bind调用来绑定数据


以下是如何在C中实现此功能:

班级计划 { 静态环[]args { 如果文件为.existest.db3 { 文件Deletetest.db3; } 使用var connection=new-SQLiteConnectionData-Source=test.db3;Version=3 using var command=new SQLiteCommandCREATE TABLE PHOTOSID INTEGER主键自动递增,PHOTO BLOB,connection { 连接。打开; command.ExecuteNonQuery; 字节[]photo=新字节[]{1,2,3,4,5}; command.CommandText=插入照片照片值@PHOTO; 命令参数。Add@photo,DbType.Binary,20.Value=photo; command.ExecuteNonQuery; command.CommandText=从ID=1的照片中选择照片; 使用var reader=command.ExecuteReader { 边读边读 { 字节[]缓冲区=GetBytesreader; } } } } 静态字节[]GetBytesSQLiteDataReader { const int CHUNK_SIZE=2*1024; 字节[]缓冲区=新字节[块大小]; 漫长的过去; 长字段偏移=0; 使用MemoryStream流=新MemoryStream { 而bytesRead=reader.GetBytes0,fieldOffset,buffer,0,buffer.Length>0 { stream.Writebuffer,0,intbytesRead; fieldOffset+=字节读取; } 返回stream.ToArray; } } }
最后,我使用以下方法插入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++中没有错误检查:< /P>
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);
#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;
}

这可以是SQLITE_静态的

这对我来说很好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);
#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语言中如何使用它?我将源代码添加到我的类中,并使用名称空间。但是您似乎使用了,所以我尝试安装了它,但没有找到designer/install.exe。我还查看了.chm文件,从中下载了System.Data.SQLite.dll,并将其添加到项目引用中。没有必要安装任何东西好的,三年后。。。但这段代码中的实际读取有什么意义?为什么不直接使用stream.Writebuffer,0,bytesRead?@Jon,关键是我的愚蠢。谢谢你的注意。立即修复。@DarinDimitrov TNX,但块大小是多少?下一个问题是:‌ 关于浮点向量呢?我一直在寻找一种与GetBytes等效的插入方法,但phxsoftware的提供者和devart.com似乎都没有办法在不将整个文件存储在内存中的情况下插入数据。首先,devart.com的SQLiteBlob看起来很有希望,但似乎不支持这一点。这应该是哪种语言?java是我当时使用的语言,这应该是哪种语言?C。我在评论中添加了这一点。作为SQLite的新手,这个答案令人惊讶!快速提问:既然这是一个只读操作,那么是否需要它/将它包含在事务中并提交它有什么好处?老实说,我认为事务与select语句结合起来没有多大意义,但这是关于它本身的主题。blobData.data是访问底层数组的C++11函数