ExecuteScalar:连接 属性 尚未初始化。 SQL 服务器连接

ExecuteScalar: Connection property has not been initialized. SQL Server Connection

我写了这段代码来读取存储在 SQL 服务器数据库中的图像,但是我得到了这个错误:

ExecuteScalar: Connection property has not been initialized.

由于我已经初始化了连接,我不确定是什么问题。

SqlConnection myConnection = null;
try
{        
    myConnection = new SqlConnection("Data Source=Source; Initial Catalog=Database; user ID=Test; Password=Test");
    SqlCommand myCommand = new SqlCommand ("SELECT imagedata FROM Database , myConnection");
    myConnection.Open();
    // Get the image from the database.   
    byte[] imagedata = (byte[])myCommand.ExecuteScalar();
    if (imagedata != null)
    {        
        return image;
    }
    else
    {      
        return null;
    }
}
finally
{       
    myConnection.Close();
}

您已将 Select 声明和连接用双引号 (") 括起来。也就是说,您实际上没有指定 SqlCommandConnection 属性。将您的 SqlCommand 更改为:

SqlCommand myCommand = new SqlCommand ("SELECT imagedata FROM Database , myConnection");

为此:

SqlCommand myCommand = new SqlCommand ("SELECT imagedata FROM Database" , myConnection);

或者像这样:

SqlCommand myCommand = new SqlCommand("SELECT imagedata FROM Database");
myCommand.Connection = myConnection;