-5

我有一个列表框,其中存储了数据库中的“名字”和“姓氏”。

如何编写查询以从选择索引的数据库中检索信息。

我有

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

虽然不工作

4

3 回答 3

1

除了 SQL 注入漏洞之外,您所拥有的看起来像是一个好的开始。我会阅读参数化查询。 这是一篇我觉得很好地涵盖了这个概念的文章。

您最终将使用 SqlConnection、SqlCommand、SqlParameter 和可能的其他一些类的组合。

于 2013-06-19T21:30:42.837 回答
1

两个词(两种方式):Parameterized QueriesPrepared Statements。你怎么称呼它取决于你喜欢哪个 - 它们的意思是一样的!使用它们可以带来性能和安全方面的好处。

我假设我在你的问题中读到这就是你所拥有的。您的listbox控件仅包含在您的数据库中找到的名称列表,这些名称与Items您的listbox.

我的解释

这不是一个可取的设计,但可以让它发挥作用,而不需要对你已有的东西进行返工。

对于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...

}

显然,您可以看到为什么这不是一个可取的设计选择,但考虑到您已经设置的内容,它会起作用。

于 2013-06-20T01:32:46.790 回答
0

这是使用 LINQ to 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>
于 2013-06-19T21:29:51.573 回答