Exitos Exitos - 7 months ago 16
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;
conn.Open();
string simpleValue = command.ExecuteReader()[0].ToString();
conn.Close();
return simpleValue;


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

Answer

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.

Comments