I wrote this code to read the images stored in SQL Server database however I got this error:
ExecuteScalar: Connection property has not been initialized.
Since I already initialized the connection, I am not sure what the problem is.
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();
}
You have put both your Select
statement and your connection in double quotes ("
). i.e you didn't specify the SqlCommand
's Connection
property actually. Change your SqlCommand
from this:
SqlCommand myCommand = new SqlCommand ("SELECT imagedata FROM Database , myConnection");
To this:
SqlCommand myCommand = new SqlCommand ("SELECT imagedata FROM Database" , myConnection);
Or like this:
SqlCommand myCommand = new SqlCommand("SELECT imagedata FROM Database");
myCommand.Connection = myConnection;