2016-03-11 2 views
0

J'ai écrit ce code pour lire les images stockées dans la base de données SQL Server mais j'eu cette erreur:ExecuteScalar: la propriété de connexion n'a pas été initialisée. Connexion SQL Server

ExecuteScalar: Connection property has not been initialized.

Depuis je l'ai déjà initialisé la connexion, je ne suis pas sûr de ce que le problème est.

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(); 
} 

Répondre

1

Vous avez mis à la fois votre déclaration Select et votre connexion entre guillemets ("). c'est-à-dire que vous n'avez pas spécifié la propriété Connection de SqlCommand réellement. Changez votre SqlCommand de ceci:

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

à ceci:

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

Ou comme ceci:

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