Chris Chris - 1 year ago 116
ASP.NET (C#) Question

Simple SQL select in C#?

On my current project, to get a single value (select column from table where id=val), the previous programmer goes through using a datarow, datatable and an sqldatadapter (and of course sqlconnection) just to get that one value.

Is there an easier way to make a simple select query? In php, I can just use

and then
and I'm done.

It would be nice if I could just do:

SqlConnection conSql = new SqlConnection(ConnStr);
SomeSqlClass obj = new SomeSqlClass(sql_string, conSql);
return obj[0];

Thanks for any tips.

Answer Source

You can skip the DataReader and the DataAdapter and just call ExecuteScalar() on the sql command.

using (SqlConnection conn = new SqlConnection(connString))
      SqlCommand cmd = new SqlCommand("SELECT * FROM whatever 
                                       WHERE id = 5", conn);
            newID = (int)cmd.ExecuteScalar();
        catch (Exception ex)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download