将图片等文件保存到sqlite中(c#)

前端之家收集整理的这篇文章主要介绍了将图片等文件保存到sqlite中(c#)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

sqli.net的dll为System.Data.sqlite.dll,这种dll分为32位、64位和适用于compactframework三种,在引用时要注意,选择正确的dll。

将要保存图片的字段类型设为blob。代码如下:

 private void savePicture()
        {
            using (sqliteConnection cnn = new sqliteConnection(dbPath))
            {
                cnn.Open();
                using (sqliteCommand cmd = cnn.CreateCommand())
                {
                    //cmd.CommandText = "Create Table test(data Image)"; 
                    //cmd.ExecuteNonQuery();
                    cmd.CommandText = "insert into person values('12',@data,'14','13')";
                    sqliteParameter para = new sqliteParameter("@data",DbType.Binary);
                    string file = @"F:\Image\飞机.png";
                    FileStream fs = new FileStream(file,FileMode.Open);
                    //StreamUtil su = new StreamUtil();
                    //byte[] buffer = su.StreamToBytes(fs);
                    byte[] buffer = StreamUtil.ReadFully(fs);
                    fs.Close();
                    para.Value = buffer;
                    cmd.Parameters.Add(para);
                    cmd.ExecuteNonQuery();
                }
            }
        }

其中StreamUtil为自定义的一个类:

public static class StreamUtil
    {
        const int BufferSize = 8192;
        public static void CopyTo(Stream input,Stream output)
        {
            byte[] buffer = new byte[BufferSize];
             
            int read;
             while ((read = input.Read(buffer,buffer.Length)) > 0)
            {
                output.Write(buffer,read);
            }
         }
         
         public static byte[] ReadFully(Stream input)      
        {   
            using (MemoryStream tempStream = new MemoryStream())
            {
                CopyTo(input,tempStream);
                return tempStream.ToArray();
            }
        }
     
    }

参考:http://www.kaiyuan8.org/Article/qfuoQyWKDicoYpoirorz.aspx
C#教程:声明和调用扩展方法http://www.webjx.com/aspnet/2009-04-12/11229.html


http://topic.csdn.net/u/20081024/09/9b2bf0ad-ec15-4b00-9994-3124038ba329.html

方法主要是利用了 sqliteParameter 的功能,读取blob字段。代码如下:

FileStream m_filestream = null; 
   
try { 
   
m_filestream = new FileStream(@"d:\pcinfo\17.jpg",FileMode.Open,FileAccess.Read); //读取图片 

sqliteCommand m_commd2=new sqliteCommand(); 
m_commd2.CommandText="UPDATE test1 set timage=@idimage WHERE tparendid=78"; 
   

Byte[] m_byte = new Byte[m_filestream.Length]; //存放图片 

m_filestream.Read(m_byte,m_byte.Length); 

m_filestream.Close(); 

sqliteParameter param_m=new sqliteParameter("@idimage",DbType.Binary,m_byte.Length,ParameterDirection.Input,false,null,DataRowVersion.Current,m_byte); 
m_commd2.Parameters.Add(param_m); m_commd2.Parameters.Add(param_m); //很多参数阿,注意DBType.Binary 
   
m_commd2.Connection = m_conn; 
m_commd2.ExecuteNonQuery(); 


   } 
catch (sqliteException ex) 
{ 

MessageBox.Show("未能存入图片"); 
   
}

猜你在找的Sqlite相关文章