如何从sqlite存储和检索blob

前端之家收集整理的这篇文章主要介绍了如何从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,buffer.Length)) > 0)
            {
                stream.Write(buffer,(int)bytesRead);
                fieldOffset += bytesRead;
            }
            return stream.ToArray();
        }
    }
}

猜你在找的Sqlite相关文章