您的位置:首页 > 数据库

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

2010-01-04 12:19 746 查看
SqLite.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, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, 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,0,m_byte.Length);

m_filestream.Close();

SQLiteParameter param_m=new SQLiteParameter("@idimage",DbType.Binary,m_byte.Length, ParameterDirection.Input,false,0,0,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("未能存入图片");
  
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: