c# - System.InvalidOperationException: '连接必须有效且打开。'

我正在使用 .NET 和 MySQL 数据库用 C# 开发程序。一旦用户登录,我需要用户图像可见,为此我有一个名为“图像”的 LONGBLOB 类型列。登录过程很好,但是出现以下错误

Connection must be valid and open.

我正在使用以下代码从数据库中进行选择:

MySqlCommand command1 = new MySqlCommand("select `user Image` from `userdb` where `username` = @img", con);
        
        command1.Parameters.Add("@img", MySqlDbType.Blob);
        
        command1.Parameters["@img"].Value = Admin;

        byte[] img = (byte[])command1.ExecuteScalar();

        if (img == null)
        {
            pic_profilePic.Image = null;
        }
        else
        {
            var DATA = (byte[])command1.ExecuteScalar();
            var stream = new MemoryStream(DATA);
            pic_profilePic.Image = Image.FromStream(stream);
        }

尽管将列类型更改为二进制和 varbinary,但我仍然遇到相同的错误。

有谁知道我在这里做错了什么?

回答1

string cs = @"server=localhost;userid=dbuser;password=s$cret;database=testdb";

var con = new MySqlConnection(cs);
con.Open(); //did you open after you initialize the connection?

请检查您的代码以打开您的连接

完成后也记得关闭它

con.Close();

相似文章

随机推荐

最新文章