Link to home
Start Free TrialLog in
Avatar of ATaiPan
ATaiPan

asked on

Help SqlCommand will not return data

I cannot seem to get this command to return data, an anyone tell me what I am doing wrong?

SqlCommand queryCommand = new SqlCommand(string.Format("Select * from table where Account = '{0}'", txtAccountInput.Text));
SqlCommand queryCommand = new SqlCommand(string.Format("Select * from table where Account = '{0}'", txtAccountInput.Text));

Open in new window

Avatar of oxyoo
oxyoo
Flag of Sweden image

Hi,

Could you post the entire C# code, the connection part as well as
where you run your command?

Thanks.
Avatar of Guy Hengel [angelIII / a3]
please try this instead, replacing the data type and size as needed:
SqlCommand queryCommand = new SqlCommand("Select * from table where Account = @acc");
SqlParameter p = new System.Data.SqlClient.SqlParameter("@acc", System.Data.SqlDbType.NVarChar, 10, txtAccountInput.Text);
queryCommand.Parameters.Add(p);

Open in new window

Avatar of ATaiPan
ATaiPan

ASKER

Well, now I have a new error "The parameterized query '(acc nvarchar(10))Select * from table where Account = @acc' expects the parameter @acc" which is not supplied.
you will need to show more code so we can see where you made the error.
SqlCommand queryCommand = new SqlCommand(string.Format("Select * from table where Account = '{0}'", txtAccountInput.Text));

after this do:

SqlDataReader Reader = queryCommand.ExecuteReader();
while(Reader.Read())
{
   // use Reader[field_name] to get the values
}
ASKER CERTIFIED SOLUTION
Avatar of oxyoo
oxyoo
Flag of Sweden image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Here is a more complete example...
using(SqlConnection connection = new SqlConnection("connectionstring") ) {
  SqlCommand command = new SqlCommand("Select * from table where Account = @acc", connection);
  command.CommandType = CommandType.Text;
  command.Parameters.AddWithValue("@acc", txtAccountInput.Text);
  connection.Open();
 
  SqlDataReader reader = command.ExecuteReader();
  while(reader.Read()) {
    // magic goes here...
  }
 
  connection.Close();
}

Open in new window