C# 从数据库获取图像到图像框

C# 从数据库获取图像到图像框,c#,C#,这是我的代码,我曾尝试从db中检索图像,但参数在内存流中无效,并且看到许多关于参数在stackoverflow上无效的答案,但我的问题是相同的 try { con = new SqlConnection(cs.DBConn); con.Open(); // Retrieve BLOB from database into DataSet. String sql = "Select Image from Users where Username='" + Txt

这是我的代码,我曾尝试从db中检索图像,但参数在内存流中无效,并且看到许多关于参数在stackoverflow上无效的答案,但我的问题是相同的

try
{
    con = new SqlConnection(cs.DBConn);
    con.Open();

    // Retrieve BLOB from database into DataSet.
    String sql = "Select  Image from Users where Username='" + TxtUserName.Text + "' and password='" + TxtPassword.Text + "'";
    cmd = new SqlCommand(sql, con);
    SqlDataReader dr = cmd.ExecuteReader();

    while (dr.Read())
    {
        byte[] b = new byte[0];
        b = (Byte[])(dr["Image"]);
        MessageBox.Show(b.ToString());
        MemoryStream ms = new MemoryStream(b);
        pictureBox1.Image = Image.FromStream(ms);
        frm.pictureBox2.Image = pictureBox1.Image;

        con.Close();
    }
}
catch (Exception ex)
{ 
    MessageBox.Show(ex.Message);
}
试着这样做:

var da = new SqlDataAdapter(cmd);
var ds = new DataSet();
da.Fill(ds, "Images");
int count = ds.Tables["Images"].Rows.Count;

if (count > 0)
{ 
    var data = (Byte[])(ds.Tables["Images"].Rows[count - 1]["Image"]);
    var stream = new MemoryStream(data);
    pictureBox1.Image= Image.FromStream(sream);
} 
试着这样做:

var da = new SqlDataAdapter(cmd);
var ds = new DataSet();
da.Fill(ds, "Images");
int count = ds.Tables["Images"].Rows.Count;

if (count > 0)
{ 
    var data = (Byte[])(ds.Tables["Images"].Rows[count - 1]["Image"]);
    var stream = new MemoryStream(data);
    pictureBox1.Image= Image.FromStream(sream);
} 

虽然其他答案可能已经解决了您手头的问题,但我想建议一些额外的优化:

try
{
    // Put your connection into a using block to have closing/disposing handled for you
    using (con = new SqlConnection(cs.DBConn))
    {
        con.Open();

        // Create a query with placeholders for your parameter values
        // Limit it with TOP 1 - since you only expect to identify 1 user
        string sql = "SELECT TOP 1 [Image] FROM [Users] WHERE [Username] = @usr AND [password] = @pwd";

        using (cmd = new SqlCommand(sql, con))
        {
            // add a parameter with the user name value
            cmd.Parameters.AddWithValue("usr", TxtUserName.Text);

            // add a parameter with the password value
            cmd.Parameters.AddWithValue("pwd", TxtPassword.Text);

            // Use ExecuteScalar since you only expect 1 row with 1 column
            byte[] b = cmd.ExecuteScalar() as byte[];

            // you may want to check if byte array b is null

            // Same as for Connection: let using handle disposing your MemoryStream
            using (MemoryStream ms = new MemoryStream(b))
            {
                pictureBox1.Image = Image.FromStream(ms);
                frm.pictureBox2.Image = pictureBox1.Image;
            }
        }
    }
}
catch (Exception ex)
{ 
    MessageBox.Show(ex.Message);
}

虽然其他答案可能已经解决了您手头的问题,但我想建议一些额外的优化:

try
{
    // Put your connection into a using block to have closing/disposing handled for you
    using (con = new SqlConnection(cs.DBConn))
    {
        con.Open();

        // Create a query with placeholders for your parameter values
        // Limit it with TOP 1 - since you only expect to identify 1 user
        string sql = "SELECT TOP 1 [Image] FROM [Users] WHERE [Username] = @usr AND [password] = @pwd";

        using (cmd = new SqlCommand(sql, con))
        {
            // add a parameter with the user name value
            cmd.Parameters.AddWithValue("usr", TxtUserName.Text);

            // add a parameter with the password value
            cmd.Parameters.AddWithValue("pwd", TxtPassword.Text);

            // Use ExecuteScalar since you only expect 1 row with 1 column
            byte[] b = cmd.ExecuteScalar() as byte[];

            // you may want to check if byte array b is null

            // Same as for Connection: let using handle disposing your MemoryStream
            using (MemoryStream ms = new MemoryStream(b))
            {
                pictureBox1.Image = Image.FromStream(ms);
                frm.pictureBox2.Image = pictureBox1.Image;
            }
        }
    }
}
catch (Exception ex)
{ 
    MessageBox.Show(ex.Message);
}

虽然这个代码片段可以解决这个问题,但它确实有助于提高文章的质量。请记住,您将在将来回答读者的问题,而这些人可能不知道您的代码建议的原因。虽然此代码片段可以解决问题,但确实有助于提高您文章的质量。请记住,您将在将来回答读者的问题,而这些人可能不知道您的代码建议的原因。您的目标是什么:Winforms、WPF、ASP。。?始终正确标记您的问题!我强烈建议您在查询中使用SqlParameter而不是字符串连接-或者,当您当前的问题得到解决时,我建议您看看“您的目标是什么:Winforms、WPF、ASP…”。。?始终正确标记您的问题!我强烈建议您在查询中使用SqlParameter而不是字符串连接,或者当您当前的问题得到解决时,我建议您查看“相同问题的参数无效”。您确定您的
图像
列甚至返回
字节[]
?尝试调试并检查从
cmd.ExecuteScalar()
返回的对象,或者更好地检查在SSMS中运行查询时返回的值。相同的问题参数无效您确定
Image
列甚至返回
字节[]
?尝试调试并检查从
cmd.ExecuteScalar()
返回的对象,或者更好地检查在SSMS中运行查询时返回的值。