Exitos Exitos - 2 years ago 67
SQL Question

How do get a simple string from a database

The following code does not work. There is only 1 row in this table. How do I just get the statement that the sql would return?:

SqlConnection conn = new SqlConnection(connectionStringArg);
SqlCommand command = new SqlCommand("select applicationname from tbl_settings");
command.Connection = conn;
string simpleValue = command.ExecuteReader()[0].ToString();
return simpleValue;

Okay any help on how to achieve this relatively simple task would be great.

Answer Source

Since there's only a single value returned, you could do this:

 string value = (string)command.ExecuteScalar();

If you need more than the first column from the first row returned, you'll need to use ExecuteReader(). See driis' answer.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download