📜  c# sql select - SQL (1)

📅  最后修改于: 2023-12-03 14:59:40.861000             🧑  作者: Mango

C# SQL SELECT - SQL

Are you looking for a tutorial on how to perform a SELECT statement in C# using SQL? Then you're in the right place!

In this guide, we will cover the basic syntax of a SELECT statement in SQL and how to execute it in C# using ADO.NET.

Basic Syntax of a SELECT Statement in SQL

The basic syntax of a SELECT statement in SQL is:

SELECT column1, column2, ...
FROM table_name
WHERE condition;

Here:

  • column1, column2, ...: the column(s) you want to retrieve data from
  • table_name: the name of the table you want to retrieve data from
  • condition: the condition(s) that must be met for the data to be retrieved (optional)
Executing a SELECT Statement in C# Using ADO.NET

To execute a SELECT statement in C# using ADO.NET, you need to follow these steps:

  1. Create a SqlConnection object and set the connection string.

    SqlConnection conn = new SqlConnection("Data Source=myServerAddress;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;");
    
  2. Open the connection to the database.

    conn.Open();
    
  3. Create a SqlCommand object and set the SELECT statement.

    SqlCommand cmd = new SqlCommand("SELECT column1, column2 FROM table_name WHERE condition", conn);
    
  4. Execute the SELECT statement and retrieve the data using a SqlDataReader object.

    SqlDataReader dr = cmd.ExecuteReader();
    
  5. Loop through the data using the Read() method of the SqlDataReader object.

    while (dr.Read())
    {
        // retrieve data using the column names or indices
        string column1Value = dr["column1"].ToString();
        string column2Value = dr[1].ToString();
    }
    
  6. Close the SqlDataReader object and the connection.

    dr.Close();
    conn.Close();
    
Conclusion

In this guide, we have learned the basic syntax of a SELECT statement in SQL and how to execute it in C# using ADO.NET. With this knowledge, you can now retrieve data from a database using C# and SQL. Happy coding!