c# - C#中如何直接执行SQL查询?

标签 c# .net sql-server batch-file

好的,我有一个旧的批处理文件可以完全满足我的需要。但是,如果没有新的管理,我们将无法再运行批处理文件,所以我需要从 C# 开始。

我使用的是 Visual Studio C#,并且已经为我需要构建的应用程序设置了表单。 (边走边学)

这是我需要在 C# 中完成的(这是批处理内容)

sqlcmd.exe -S .\PDATA_SQLEXPRESS -U sa -P 2BeChanged! -d PDATA_SQLEXPRESS  -s ; -W -w 100 -Q "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday  FROM  [dbo].[TPatientRaw] WHERE tPatSName = '%name%' "

基本上,它使用 SQLCMD.exe 和名为 PDATA_SQLExpress 的现有数据源。
我已经搜索并接近了,但我仍然不知道从哪里开始。

最佳答案

要直接从 C# 中执行您的命令,您可以使用 SqlCommand类。

使用参数化 SQL(以避免注入(inject)攻击)的快速示例代码可能如下所示:

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

关于c# - C#中如何直接执行SQL查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21709305/

相关文章:

c# - iOS 应用程序启动错误

c# - 在 MVC 中向我的编辑 Controller 添加删除功能

c# - 包含 IDisposable 成员的 WPF 控件

c# - 使用 .NET 进行 JSON 和 Base64 编码

sql - LAG 所有先前行 - 父子数据库查找每个父项的所有子项总数

c# - LINQ 方法是扩展方法吗?

c# - 如何合并 Html.ActionLink (MVC3) 的 htmlAttributes?

.net - 在 .NET 中使用私钥对文件进行签名

sql-server - SSIS 条件拆分未按预期工作

SQL 代理无法处理系统日期更改?