Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 303
Chris Avatar asked Oct 01 '09 16:10

Chris


People also ask

What is select in SQL with example?

The SELECT TOP statement is used to limit the number of rows which returns the result of the query. For example, if want to retrieve only two rows from the table we can use the following query. Therefore, we can limit the result set of the query. In the following SQL examples, we will limit the result set of the query.

Can I use SQL in C?

You can code SQL statements in a C or C++ program wherever you can use executable statements. Each SQL statement in a C or C++ program must begin with EXEC SQL and end with a semicolon (;). The EXEC and SQL keywords must appear on one line, but the remainder of the statement can appear on subsequent lines.

What is a simple select query?

A select query helps you retrieve only the data that you want, and also helps you combine data from several data sources. You can use tables and other select queries as data sources for a select query.


2 Answers

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);
        }
 }
like image 81
womp Avatar answered Sep 24 '22 05:09

womp


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();
}
like image 38
Kristoffer Deinoff Avatar answered Sep 23 '22 05:09

Kristoffer Deinoff