2013-06-19 21 views
-5

我有一個列表框,其中存儲着'firstname'和'lastname'的數據庫。從文本框中選擇數據庫值

我該如何編寫我的查詢以從數據庫中檢索選擇索引的信息。

"Select * from table where firstname= '"+listbox1.Text+"' and lastname= '"+listbox1.Text+"' " 

不工作雖然

+0

什麼不行? –

+0

請您澄清一下您的問題。名字和姓氏在你的'listbox'中,並且來源於數據庫,但是一些細節會很好。 –

回答

0

這裏是一個 「其中」 使用LINQ時,SQL ...

<asp:LinqDataSource 
      ContextTypeName="YourDataContext" 
      TableName="YourTable" 
      ID="DataSource" 
      runat="server" 
      Where="FirstName == @FN"> 
      <WhereParameters> 
       <asp:ControlParameter Name="FN" ControlID="LISTBOX" 
             Type="String" PropertyName="Text" /> 
      </WhereParameters> 
</asp:LinqDataSource> 
1

你有什麼看起來像一個良好的開端一邊來自SQL注入漏洞。我會閱讀參數化查詢。我覺得這個概念很好地覆蓋了我的This is an article

您將最終使用的SqlConnection,SqlCommand的,SqlParameter的組合,也許一些其他類。

1

兩個詞(雙向):Parameterized QueriesPrepared Statements。你稱之爲什麼取決於你更喜歡哪一個 - 它們意味着相同的東西!使用它們會帶來性能和安全方面的好處。

我假設我讀過你的問題,這就是你所擁有的。如果您的listbox控件只包含在您的數據庫中找到的名稱列表,這些名稱在您的listbox中僅包含爲Items

My interpretation

這不是一個明智的設計,但讓令其功能沒有什麼您已經有一個返工。

對於SQL ServerC#,代碼會是這樣:

string commandText = "SELECT * FROM table WHERE firstname = @firstname and lastname = @lastname"; 
using (SqlConnection connection = new SqlConnection(connectionString)) 
{ 
    SqlCommand command = new SqlCommand(commandText, connection); 
    if (listbox1.SelectedItem == null) 
    { 
     // exit since nothing was selected in the listbox to query by 
    } 
    var names = listbox1.SelectedItem.ToString().Split(' '); 
    if (names.Length != 2) 
    { 
     // exit since this is not what we want and will yield unexpected results 
    } 
    string firstName = names[0]; 
    string lastName = names[1]; 
    command.Parameters.AddWithValue("@firstname", firstname); 
    command.Parameters.AddWithValue("@lastname", lastname); 

    // Read information from database... 

} 

顯然,你可以看到爲什麼這不是一個明智的設計選擇,但它會工作給予你已經完成的設置。

相關問題