使用带参数的sql语句实现添加功能
public static void InsertPic(string filename)
{
string sql = "insert into ImgTest(Name,Sculpture) values(@Name,@Sculpture)";
byte[] ib = new Byte[10486760];
FileStream fs = new FileStream(@filename, FileMode.Open, FileAccess.Read);
fs.Read(ib, 0, 10486760);
SqlParameter[] param = new SqlParameter[]
{
new SqlParameter("Name", SqlDbType.VarChar, 50),
new SqlParameter("@Sculpture", SqlDbType.Image, (int)fs.Length)
};
param[0].Value = "AA";
param[1].Value = ib;
int result = SQLHelper.Update(sql, param);
}
根据名称返回单一图片
public static Image GetPic(string Id)
{
SqlConnection conn = new SqlConnection(connString);
conn.Open();
string sql = "select Sculpture from ImgTest where Name = '{0}'";
sql = string.Format(sql, Id);
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
MemoryStream buf = new MemoryStream((byte[])reader[0]);
Image image = Image.FromStream(buf, true);
return image;
}
修改特定对象的图片内容
public static void Change(string filename,string Name)
{
string sql = "update ImgTest set Sculpture = @Sculpture where Name = @Name";
byte[] ib = new Byte[10486760];
FileStream fs = new FileStream(@filename, FileMode.Open, FileAccess.Read);
fs.Read(ib, 0, 10486760);
SqlParameter[] param = new SqlParameter[]
{
new SqlParameter("Name", SqlDbType.VarChar, 50),
new SqlParameter("@Sculpture", SqlDbType.Image, (int)fs.Length)
};
param[0].Value = Name;
param[1].Value = ib;
int result = SQLHelper.Update(sql, param);
}
从数据库中获取某图片
public static Image GetPic(string Id)
{
SqlConnection conn = new SqlConnection(connString);
conn.Open();
string sql = "select Sculpture from ImgTest where Name = '{0}'";
sql = string.Format(sql, Id);
SqlCommand cmd = new SqlCommand(sql, conn);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
MemoryStream buf = new MemoryStream((byte[])reader[0]);
Image image = Image.FromStream(buf, true);
return image;
}
从数据库中获取图片组
string sql1 = "select Sculpture from ImgTest";
DataSet ds1 = SQLHelper.GetDataSet(sql1);
foreach (DataRow item in ds1.Tables[0].Rows)
{
obj.Add(ImageConvert.ArryToPic((byte[])item.ItemArray[0]));
}
将含图片的DateSet映射到控件
string sql = "select *from ImgTest";
DataSet ds = SQLHelper.GetDataSet(sql);
DataShow.DataSource = ds.Tables[0];
效果
附测试工程文件:https://download.csdn.net/download/weixin_37878740/12293188