Home > Backend Development > C++ > How Can I Execute SQL Queries Directly Within My C# Application?

How Can I Execute SQL Queries Directly Within My C# Application?

Linda Hamilton
Release: 2025-01-04 07:37:35
Original
675 people have browsed it

How Can I Execute SQL Queries Directly Within My C# Application?

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();
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template