Executing SQL Queries Directly in C#
Many developers encounter the need to execute SQL queries directly within their C# applications. This can be achieved using the SqlCommand class.
To execute a query using SqlCommand, you must first create a connection to the database. This is done by creating a SqlConnection object and specifying the connection string, which contains the necessary information to establish the connection.
Once the connection is established, you can create a SqlCommand object and specify the query string. You can also add parameters to the SqlCommand object to prevent SQL injection attacks.
To execute the query, call the ExecuteReader() method of the SqlCommand object. This will return a SqlDataReader object, which contains the results of the query. You can use the SqlDataReader to iterate through the results and retrieve the data.
Here is an example of how to execute a SQL query directly in C#:
string queryString = "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday FROM [dbo].[TPatientRaw] WHERE tPatSName = @tPatSName"; string connectionString = "Server=.\PDATA_SQLEXPRESS;Database=;User Id=sa;Password=2BeChanged!;"; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(queryString, connection); command.Parameters.AddWithValue("@tPatSName", "Your-Parm-Value"); connection.Open(); SqlDataReader reader = command.ExecuteReader(); try { while (reader.Read()) { Console.WriteLine(String.Format("{0}, {1}", reader["tPatCulIntPatIDPk"], reader["tPatSFirstname"]));// etc } } finally { // Always call Close when done reading. reader.Close(); } }
The above is the detailed content of How Can I Execute SQL Queries Directly Within My C# Application?. For more information, please follow other related articles on the PHP Chinese website!