📅  最后修改于: 2023-12-03 14:59:40.861000             🧑  作者: Mango
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.
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 fromtable_name
: the name of the table you want to retrieve data fromcondition
: the condition(s) that must be met for the data to be retrieved (optional)To execute a SELECT statement in C# using ADO.NET, you need to follow these steps:
Create a SqlConnection
object and set the connection string.
SqlConnection conn = new SqlConnection("Data Source=myServerAddress;Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;");
Open the connection to the database.
conn.Open();
Create a SqlCommand
object and set the SELECT statement.
SqlCommand cmd = new SqlCommand("SELECT column1, column2 FROM table_name WHERE condition", conn);
Execute the SELECT statement and retrieve the data using a SqlDataReader
object.
SqlDataReader dr = cmd.ExecuteReader();
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();
}
Close the SqlDataReader
object and the connection.
dr.Close();
conn.Close();
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!