【发布时间】:2015-06-08 15:02:58
【问题描述】:
我使用了两年前在 VB 中完成的代码,将几乎所有代码都转换为在 c# 环境中工作,尽管我在最后一部分遇到了障碍,因为我不知道如何处理它。
以前的VB代码
If Not binGotOne Then
strSQL = Mid$(strSQL, 1, InStr(strSQL, "WHERE") - 1)
End If
当前的 C# 代码
/* This section I belive is substrings though I'm not sure,
currently I can't get it to work as I'm not sure how to apporach it*/
if (!filter)
{
query = (query, 1,(query, "WHERE") - 1);
}
c# 部分是下面显示的完整功能的最后一部分,我似乎无法理解。
SqlConnection connection = new SqlConnection();
Security security = new Security();
try
{
connection.ConnectionString = connectionPath;
connection.Open();
Boolean filter = false;
string query = string.Format("SELECT * FROM Staff WHERE ");
if (txtstaffid.Text != null)
{
filter = true;
query = query + "Staff_StaffId = " + txtstaffid.Text + "'";
}
else if (cbotitle.Text != null)
{
filter = true;
query = query + "Staff_Title = '" + cbotitle.Text + "";
}
else if (cborole.Text != null)
{
filter = true;
query = query + "Staff_Role = '" + cborole.Text + "'";
}
else if (txtfname.Text != null)
{
filter = true;
query = query + "Staff_Firstname = '" + txtfname.Text + "'";
}
else if (txtsname.Text != null)
{
filter = true;
query = query + "Staff_Surname = '" + txtsname.Text + "'";
}
else if (txtpostcode.Text != null)
{
filter = true;
query = query + "Staff_Postcode = '" + txtpostcode.Text + "'";
}
else if (txtemail.Text != null)
{
filter = true;
query = query + "Staff_Email = '" + txtemail.Text + "'";
}
/* This section I belive is substrings though I'm not sure,
currently I can't get it to work as I'm not sure how to apporach it*/
if (!filter)
{
query = (query, 1, (query, "WHERE") - 1);
}
SqlCommand cmd = new SqlCommand(query, connection);
SqlDataAdapter dap = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dap.Fill(ds);
BindingSource bs = new BindingSource();
bs.DataSource = ds.Tables[0];
dgv.DataSource = bs;
dap.Update(ds);
}
catch (SqlException sql)
{
MessageBox.Show(sql.Message);
}
finally
{
connection.Close();
connection.Dispose();
}
【问题讨论】:
-
我的 StaffId 是
1 OR 1=1 --... 阅读有关 SQL 注入和一般数据访问的信息。手动编写 SQL 字符串被认为是有害且过时的。 -
我知道最后一部分有点过时了,我打算改变它,谢谢