且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检索与System.Data.SQLite和C#中的BLOB

更新时间:2023-02-09 08:14:43

确定,这里就是我已经添加和检索斑点。

ok, here's how i have added and retrieved blobs.

我想这一切都取决于byte []的是否是可管理的大小。这个工作对小物体被序列化到数据库中。

i suppose it all depends on whether the byte[] is a manageable size. This worked for small objects being serialized to the database.

使用GetDataTable来获取数据,然后有问题的行提取的字节数组以下内容:

use GetDataTable to get the data and then on the row in question extract the byte array with the following:

    public byte[] getByteArray(DataRow row, int offset)
    {
        object blob = row[offset];
        if (blob == null) return null;
        byte[] arData = (byte[])blob;
        return arData;
    }

这是我如何添加它们:

    private System.Object syncLock = new System.Object();

    public int ExecuteNonQueryWithBlob(string sql, string blobFieldName, byte[] blob)
    {
        lock (syncLock)
        {
            try
            {
                using (var c = new SQLiteConnection(dbConnection))
                {
                    using (var cmd = new SQLiteCommand(sql, c))
                    {
                        cmd.Connection.Open();
                        cmd.Parameters.AddWithValue("@" + blobFieldName, blob);
                        return cmd.ExecuteNonQuery();
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return 0;
            }
        }
    }

    public DataTable GetDataTable(string sql)
    {
        lock (syncLock)
        {
            try
            {
                DataTable dt = new DataTable();
                using (var c = new SQLiteConnection(dbConnection))
                {
                    c.Open();
                    using (SQLiteCommand cmd = new SQLiteCommand(sql, c))
                    {
                        using (SQLiteDataReader rdr = cmd.ExecuteReader())
                        {
                            dt.Load(rdr);
                            return dt;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return null;
            }
        }
    }