代码改变世界

读/写byte[] 类型 MS SQL数据库

2012-03-07 13:20  小sa  阅读(665)  评论(0编辑  收藏  举报
 //写入流
public void Write(byte[] val)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();

using (SqlCommand cmd = new SqlCommand("INSERT INTO Temp_Compress( BinData ) VALUES (@binaryValue)", con))
{
cmd.Parameters.Add("@binaryValue", SqlDbType.VarBinary).Value = val; //此处注意写入类型
cmd.ExecuteNonQuery();
}
}
}

//读取流
public object Get(int id)
{
object ret = null;
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();

using (SqlCommand cmd = new SqlCommand("Select BinData from Temp_Compress where id =@id", con))
{

cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
SqlDataReader dr= cmd.ExecuteReader();
while (dr.Read())
{
ret=dr[0];
}
}
}
return ret;
}