我编写了以下代码,将图片从数据库传递到c#中的图片框。我从微软获得了这个代码。那是该页面的网址。Microsoft
当我运行此代码时,它的显示参数无效。
这段代码有什么问题?
private void button2_Click(object sender, EventArgs e)
{
try
{
String strCn =@"Data Source=DESKTOP-ROF2H0M\BHAGI;Initial Catalog=Golden;Integrated Security=True";
SqlConnection cn = new SqlConnection(strCn);
cn.Open();
//Retrieve BLOB from database into DataSet.
SqlCommand cmd = new SqlCommand("SELECT User_id ,img FROM login", cn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "login");
int c = ds.Tables["login"].Rows.Count;
if (c > 0)
{ //BLOB is read into Byte array, then used to construct MemoryStream,
//then passed to PictureBox.
Byte[] byteBLOBData = new Byte[0];
byteBLOBData = (Byte[])(ds.Tables["login"].Rows[c-1]["img"]);
MemoryStream stmBLOBData = new MemoryStream(byteBLOBData);
pictureBox1.Image = Image.FromStream(stmBLOBData);
}
cn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
我收到以下错误消息。
未处理的类型' System.ArgumentException'发生在 System.Drawing.dll程序
附加信息:参数无效。
这是我的数据库的快照。 LOgin Table
答案 0 :(得分:2)
您有3个问题(性能和安全问题):
private void button2_Click(object sender, EventArgs e)
{
string strCn = @"Data Source=DESKTOP-ROF2H0M\BHAGI;Initial Catalog=Golden;Integrated Security=True";
using (var cn = new SqlConnection(strCn))
{
try
{
cn.Open();
using (var cmd = new SqlCommand("SELECT User_id ,imgUrlOnDisk FROM login", cn))
{
using (var dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
if (dr.Read())
{
pictureBox1.Image = Image.FromFile(Convert.ToString(dr["imgUrlOnDisk"]));
}
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (cn.State != ConnectionState.Closed)
{
cn.Close();
}
}
}
}
我建议您使用ADO.net查询的最佳方式是:
try
{
using (SqlCommand cmd = new SqlCommand(Query, Connection))
{
try
{
cmd.CommandType = CommandType;
foreach (var p in InParameters)
{
cmd.Parameters.Add(p);
}
cmd.Connection.Open();
affectedRows = cmd.ExecuteNonQuery();
if (affectedRows == 0)
{
//Zero Record Success
}
else
{
if (affectedRows > 1)
{
//Many Record Success
}
else
{
//One Record Success
}
}
}
catch (Exception InnerEx)
{
//Handle your error
}
finally
{
if (cmd.Connection.State != ConnectionState.Closed)
{
cmd.Connection.Close();
}
}
}
}