如何在C#中直接执行SQL查询? [英] How to directly execute SQL query in C#?

查看:662
本文介绍了如何在C#中直接执行SQL查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好,我有一个完全符合我需要的旧批处理文件。但是,由于没有进行新的管理,我们无法再运行批处理文件,因此我需要使用C#来启动。

Ok, I have an old batch file that does exactly what I need. However, with out new administration we can't run the batch file anymore so I need to start up with C#.

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

I'm using Visual Studio C# and already have the forms set up for the application I need to build. (I'm learning as I go)

这是我需要在C#中完成的工作(这是批处理胆量)

Here is what I need to accomplish in C# (This is the batch guts)

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

我已经搜索并接近了,但我仍然不知该从哪里开始。

Basically it uses SQLCMD.exe with the already existing datasource called PDATA_SQLExpress.
I've searched and gotten close but I'm still at a loss on where to start.

推荐答案

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

To execute your command directly from within C#, you would use the SqlCommand class.

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

Quick sample code using paramaterized SQL (to avoid injection attacks) might look like this:

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#中直接执行SQL查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆