文件流将数据读取到数据库

1.如何将文件读取到数据库保存起来,参考链接 http://bbs.csdn.net/topics/280014809

写入
string fileName = Server.MapPath("a.jpg");
FileInfo fi = new FileInfo(fileName);
FileStream fs = fi.OpenRead();
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
NpgsqlConnection con = new NpgsqlConnection(constr);
con.Open();
NpgsqlCommand cm = new NpgsqlCommand();
cm.Connection = con;
cm.CommandType = CommandType.Text;
cm.CommandText = "insert into test (filename) values(@file)";
NpgsqlParameter spFile = new NpgsqlParameter("@file", NpgsqlTypes.NpgsqlDbType.Bytea);
spFile.Value = bytes;//SqlDbType.Image
cm.Parameters.Add(spFile);
cm.ExecuteNonQuery();

 读取

NpgsqlConnection con = new NpgsqlConnection(constr);
con.Open();
string sql = "select filename from test where id=20 ";
NpgsqlCommand cm = new NpgsqlCommand(sql, con);
Byte[] bytes = (Byte)cm.ExecuteScalar();
System.IO.StreamWriter sw = System.IO.File.CreateText("d://aaa.jpg");

sw.Write(cm.ExecuteScalar());
sw.Close();
con.Close();

你可能感兴趣的:(数据库)