以下是我的按钮的代码。
private void btnStudentLookup_Click(object sender, EventArgs e)
{
string strConnect = "Server=DESKTOP-
2Q73COU\\SQLEXPRESS;Database=LoginApp;Trusted_Connection=True;";
SqlConnection conn = new SqlConnection(strConnect);
conn.Open();
using (SqlConnection studentLookup = new SqlConnection(strConnect))
{
SqlCommand command =
new SqlCommand("SELECT * FROM Main_Information WHERE [First Name] like '%" + txtFirstName.Text + "%';", studentLookup);
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataTable dt = new DataTable();
adapter.Fill(dt);
dgvAdvisor.DataSource = dt;
}
}
以上一切都有效。它根据名字过滤出行。但是,我想过滤掉更多内容,因此我将其添加到该行:
"SELECT * FROM Main_Information WHERE [First Name] like '%" + txtFirstName.Text + "%' OR [Last Name] like '%" + txtLastName.Text + "%';", studentLookup
现在它什么也没做。没有错误,没有例外,没有。有什么建议吗?
答案 0 :(得分:1)
更改查询如下:
SELECT * FROM Main_Information WHERE [First Name]如'%'+ txtFirstName.Text +“%' AND [姓氏]如'%'+ txtLastName.Text +”%';“ ,studentLookup
使用AND运算符代替OR。
答案 1 :(得分:0)
测试您的应用时,请在txtFirstName
文本框中填写:
'; DELETE FROM Main_Information; --
然后按"提交"按钮。
如果一切正常,那么如果没有,那么使用SqlParameters
来构建具有动态值的查询
using (var connection = new SqlConnection(connectionString))
using (var command = connection.CreateCommand())
{
var query = @"
SELECT * FROM Main_Information
WHERE [First Name] LIKE @firstName AND [Last Name] LIKE @lastName";
var parameters = new []
{
new SqlParameter
{
ParameterName = "@firstName",
SqlDbType = SqlDbType.VarChar,
Value = $"%{txtFirstName.Text}%"
},
new SqlParameter
{
ParameterName = "@lastName",
SqlDbType = SqlDbType.VarChar,
Value = $"%{txtLastName.Text}%"
}
}
command.CommandText = query;
command.Parameters.AddRange(parameters);
connection.Open();
var adapter = new SqlDataAdapter(command);
var data = new DataTable();
adapter.Fill(data);
dgvAdvisor.DataSource = data;
}