gpt4 book ai didi

c# - c#中的参数无效异常

转载 作者:太空狗 更新时间:2023-10-29 23:37:00 26 4
gpt4 key购买 nike

我编写了以下代码以将图片从数据库传递到 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);
}
}

我收到以下错误消息。

An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll

Additional information: Parameter is not valid.

这是我的数据库快照。 LOgin Table

最佳答案

您有 3 个问题(性能和安全问题):

  1. 你需要处理SQL连接
  2. 您需要在磁盘上存储文件(二进制和图像)(无数据库)
  3. 切勿尝试在不加密的情况下存储用户密码(如 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();
}
}
}
}

关于c# - c#中的参数无效异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39423911/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com