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

How Can I Directly Execute SQL Queries within a C# Application?

Susan Sarandon
Susan SarandonOriginal
2025-01-04 22:54:43358browse

How Can I Directly Execute SQL Queries within a C# Application?

Directly Executing SQL Queries in C#

When pursuing a new development task, it's crucial to adapt existing solutions to constraints. In the case where running a batch file is no longer feasible, we turn to C# for an alternative. Our goal is to replicate the functionality of executing an SQL query directly from within our C# application.

Using the SqlCommand class, we can execute SQL statements from within our code. Consider the following sample code:

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

By embracing this approach, we gain the power to execute SQL queries directly in our C# code, effectively mimicking the functionality of executable batch files while leveraging the flexibility, control, and performance benefits of C#.

The above is the detailed content of How Can I Directly Execute SQL Queries within a C# Application?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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