Home > Backend Development > C++ > How Can I Execute SQL Queries Directly in C# Without Using SQLCMD.exe?

How Can I Execute SQL Queries Directly in C# Without Using SQLCMD.exe?

Patricia Arquette
Release: 2025-01-05 15:09:39
Original
582 people have browsed it

How Can I Execute SQL Queries Directly in C# Without Using SQLCMD.exe?

Executing SQL Queries Directly in C#

Problem:

Current systems prohibit the execution of batch files that leverage SQLCMD.exe, requiring an alternative appraoch in C#.

Solution:

Utilizing the SqlCommand Class:

To execute SQL queries directly from C#, you can employ the SqlCommand class. This class enables you to construct and execute parameterized SQL commands, thereby avoiding injection attacks.

Example Code:

The following sample code demonstrates how to use SqlCommand with parameterized SQL:

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
    {
        reader.Close();
    }
}
Copy after login

This code connects to the specified SQL Server instance and opens a connection. It then creates a SqlCommand object using the parameterized SQL query and adds the relevant parameter to the command. The connection is opened, the query is executed, and the results are retrieved using a SqlDataReader object.

Please note that error handling and connection closing should be implemented in practical applications.

The above is the detailed content of How Can I Execute SQL Queries Directly in C# Without Using SQLCMD.exe?. 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