将图片等文件保存到sqlite中(c#)
发布时间:2020-12-12 20:23:10 所属栏目:百科 来源:网络整理
导读:sqli.net的dll为System.Data.SQLite.dll,这种dll分为32位、64位和适用于compactframework三种,在引用时要注意,选择正确的dll。 将要保存图片的字段类型设为blob。代码如下: private void savePicture() { using (SQLiteConnection cnn = new SQLiteCon
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 FileStream m_filestream = null; try { m_filestream = new FileStream(@"d:pcinfo17.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("未能存入图片"); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |