如何直接在C#中执行SQL查询?有例如批处理文件 [英] How to directly execute SQL query in C#? Have example batch file

查看:303
本文介绍了如何直接在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_SQLEx preSS
我已经搜查,并得到接近,但我仍然在就从哪里开始亏损。

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#执行您的命令,你可以使用<一个href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand%28v=vs.110%29.aspx">SqlCommand类。

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

快速样品$ c。使用paramaterized SQL(以避免注入攻击)可能是这样的$ C:

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天全站免登陆