2015-08-17 50 views
0

我正在嘗試根據用戶輸入到應用程序中的名字和姓氏來查找訂單號。我對C#非常陌生,我只是試圖爲用戶編寫一個簡單的程序來快速拉取訂單#。如何在SQL select語句中使用來自ReadLine的響應?

由於事先

賈裏德

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

您正在尋找的SqlCommand的參數性能。你可以在這裏閱讀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); 
+0

這工作完美。謝謝Vahlkron –