15

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 mysql_query and then mysql_result 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);
conSql.Close();
return obj[0];

Thanks for any tips.

6
  • 2
    Since you were asking for not only solutions, but also tips, I'd like to recommend you to take a look at LINQ, which is not only for database queries, but helps a lot! Commented Oct 1, 2009 at 16:13
  • 11
    +1: I must admire the alliteration in the question title Commented Oct 1, 2009 at 16:14
  • Also recommend the Enterprise Library Data Block. It makes simple work of most db calls. msdn.microsoft.com/en-us/library/dd203099.aspx Commented Oct 1, 2009 at 16:19
  • Thanks, I'll take a look at those tools. Commented Oct 1, 2009 at 16:31
  • 1
    Chris - it looks extremely verbose and ridiculous to start with, but most developers move these formalities into a data access layer (using a pattern such as Repository). The end result is only one or two lines of code to get everything you need. Combine this with LINQ and it's faster, less code, and maybe even more powerful than PHP. Commented Oct 1, 2009 at 17:09

5 Answers 5

41

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);
        try
        {
            conn.Open();
            newID = (int)cmd.ExecuteScalar();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
 }
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, I'll probably use this solution for now. Thank you!
A point to be noted here, ExecuteScalar returns the first row of the first column in the result. It is better to use field name explicitly. Something like this is even better select top 1 MyField ... sort by asc/desc to get the required single value.
Add this namespace using System.Data.SqlClient;
Really, really nice and simple. Most of my stuff doesn't require single values. Thanks for the quick and easy one.
9

You are probably looking for SqlCommand and SqlDataReader

Dictionary<int, string> users = new Dictionary<int, string>();
using(SqlConnection connection = new SqlConnection("Your connection string"))
{
    string query = "SELECT UserId, UserName FROM Users";
    SqlCommand command = new SqlCommand(query, connection);
    connection.Open();
    using (SqlDataReader reader = command.ExecuteReader())
    {
        while (reader.Read())
            users.Add(reader.GetInt32(0), reader.GetString(1));
    }
    connection.Close();
}

1 Comment

+1 for using the reader. But you shouldn't use column indexes!!! Also, you don't need the connection.Close (It is taken care of with the "using" statement.)
5

Actually, there is a method SqlCommand.ExecuteScalar() that will simply return the first field from the first row of the returned results. Just for you.

.NET Framework Class Library SqlCommand..::.ExecuteScalar Method

Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

Comments

4

You can do something very similar:

using (SqlConnection conn = new SqlConnection(ConnStr))
using (SqlCommand cmd = new SqlCommand(sql_string, conn))
{
    conn.Open();
    return cmd.ExecuteScalar();
}

Comments

3

you can use SqlCommands executeScalar function. Please look at the following link

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.