gpt4 book ai didi

c# - 在 SQL 查询中包含文本框值

转载 作者:行者123 更新时间:2023-11-30 22:06:22 26 4
gpt4 key购买 nike

我正在尝试使用文本框和搜索按钮搜索 GridView。我想我需要一个类似

的查询
SELECT employeeID, name, position, hourlyPayRate 
FROM dbo.employee
WHERE name LIKE 'textBox1.text+'

我在 visual studio 2013 中使用查询设计器进行了查询。

然后我有一个这样的事件处理程序

private void btnSearch_Click(object sender, EventArgs e)
{
this.employeeTableAdapter.FillBy(this.personnelDataSet.employee);
}

我确定问题出在查询中,但我只是不知道如何将文本框的值包含到查询中。

最佳答案

只需更改您的查询,它应该如下所示:

string textboxValue = textbox1.Text;
string query = "SELECT employeeID, name, position, hourlyPayRate " +
"FROM dbo.employee " +
"WHERE name LIKE '" + textboxValue + "'";

但这很容易受到 SQL 注入(inject)攻击,你应该使用 SqlCommandparameters :

string commandText = "SELECT employeeID, name, position, hourlyPayRate " +
"FROM dbo.employee WHERE name LIKE '%'+ @Name + '%'";

using (SqlConnection connection = new SqlConnection(connectionString))
{
//Create a SqlCommand instance
SqlCommand command = new SqlCommand(commandText, connection);
//Add the parameter
command.Parameters.Add("@Name", SqlDbType.VarChar, 20).Value = textbox1.Text;

//Execute the query
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch
{
//Handle exception, show message to user...
}
finally
{
connection.Close();
}
}

更新:

要在单击按钮时执行此代码,请将代码放在此处(确保您有一个名称为 YourButton 的按钮):

private void YourButton_Click(object sender, EventArgs e)
{
//Place above code here
}

更新2:

您应该在 SqlConnection 中使用一个连接字符串,该字符串可能类似于:

string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";

在这里,您必须将以 my 开头的值替换为您自己的值。有关 SQL Server 连接字符串的更多信息/示例:

关于c# - 在 SQL 查询中包含文本框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23674028/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com