如何在SQL select语句中使用ReadLine的响应?

时间:2015-08-17 18:43:08

标签: c# sql-server

我正在尝试根据用户输入应用程序的名字和姓氏查找订单号。我对C#非常陌生,我只是想为用户编写一个简单的程序来快速提取订单#。

先谢谢,

贾里德

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication4
{ 
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please Enter First Name");
            String FirstName = Console.ReadLine();
            Console.WriteLine("Please Enter Your Last Name");
            String LastName = Console.ReadLine();
            SqlConnection conn = new      SqlConnection("Server=.\\SQLEXPRESS;Database=PropertyTax;Integrated Security=true"); 
            conn.Open();
            SqlCommand cmd = new SqlCommand("Select First_Name, Order_Number From [PropertyTax].[dbo].[Sheet1$] Where First_Name = FirstName and Last_Name = LastName ", conn);
            SqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
            {
                Console.WriteLine("{0}, {1}", reader.GetString(0), reader.GetString(1));
            }
            reader.Close();
            conn.Close();
            if (Debugger.IsAttached)
            {
                Console.ReadLine();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您正在寻找SqlCommand的Parameters属性。您可以在此处阅读MSDN:

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.parameters(v=vs.110).aspx

基本上,您需要为用户输入添加一个参数,如下所示:

cmd.Parameters.AddWithValue("@FirstName", FirstName);
cmd.Parameters.AddWithValue("@LastName", LastName);

在您的查询中,您需要更新语句以使用新的@变量:

SqlCommand cmd = new SqlCommand("Select First_Name, Order_Number From [PropertyTax].[dbo].[Sheet1$] Where First_Name = @FirstName and Last_Name = @LastName", conn);