参数无效,c#异常
本文关键字:异常 无效 参数 | 更新日期: 2023-09-27 18:06:31
我写了下面的代码,用c#将图片从数据库传递到图片框。我从微软得到了这个代码。这是那个页面的url。微软
当我运行这段代码时,它的显示参数是无效的异常。
这段代码有什么问题?
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
附加信息:参数不合法。
这是我的数据库快照。登录表
你有三个问题(性能&安全问题):
- 你需要处理SQL连接
- 你需要存储文件(二进制&磁盘(无数据库)
- 永远不要尝试在没有加密的情况下存储用户密码(如MD5)
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();
}
}
}
}