在控制台应用程序C#中调用存储过程值 [英] Calling stored procedure values into the console application C#

查看:84
本文介绍了在控制台应用程序C#中调用存储过程值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个存储过程,该存储过程由C#中的控制台应用程序调用。该存储过程具有要执行的某些必需参数。
我要实现的目标是一旦执行控制台后便能够在控制台中输入所需的参数之一。

I have a stored procedure that its been called by a console application in C#. The stored procedure has some required parameters to be executed. What I am trying to achieve its to be able to enter one of the required parameters into the console once the console is executed.

有点像输入文本进入控制台,要求输入项目名称,然后按Enter。

Something like having a text into the console asking to enter the project name and then hit on enter.

这是我的代码:

try
{
    using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Test"].ConnectionString))
    {
        string outCsvFile = @"D:\\test\\test.csv";

        SqlCommand sqlCmd = new SqlCommand();
        sqlCmd.CommandType = CommandType.StoredProcedure;
        sqlCmd.Connection = conn;
        sqlCmd.CommandText = "projects";
        //Adding values to the stored procedure
        sqlCmd.Parameters.AddWithValue("@ProjectTitle", "Test Project 1"); //this value I would like to add it when the console application is executed when I will hit on enter.
        sqlCmd.Parameters.AddWithValue("@Category", "");

        conn.Open();

        SqlDataReader reader = sqlCmd.ExecuteReader();
        using (System.IO.StreamWriter file = new System.IO.StreamWriter(outCsvFile)) 
            {
                file.WriteLine(reader.GetName(0) + ',' + reader.GetName(1));

            while (reader.Read())
                file.WriteLine(reader[0].ToString() + ',' + reader[1].ToString());
               }

        conn.Close();
    }

}
catch (Exception e) 
{ 
    Console.WriteLine(e.Message);
    System.Threading.Thread.Sleep(8000);
}


推荐答案

如果我理解下面的问题是您的代码。

If I understand your question below is the code for you.

    //Adding values to the stored procedure
                Console.WriteLine("Please enter project title and press Enter");

                string projectTitle = Console.ReadLine();
                while (String.IsNullOrWhiteSpace(projectTitle))
                {
                    Console.WriteLine("Please enter project title and press Enter");
                    projectTitle = Console.ReadLine();
                }


                string outCsvFile = string.Format(@"D:\\test\\{0}.csv", projectTitle);
                if (System.IO.File.Exists(outCsvFile))
                {
                    throw new ApplicationException("File already exist Name " + outCsvFile);
                }
                sqlCmd.Parameters.AddWithValue("@ProjectTitle", projectTitle); //this value I would like to add it when the console application is executed when I will hit on enter.

这篇关于在控制台应用程序C#中调用存储过程值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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