我已经使用过两年前我在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();
}
答案 0 :(得分:2)
看起来这部分代码的工作就是删除" WHERE"如果没有添加过滤器,请从SQL中获取。对c#的字面翻译将是......
sql = sql.Substring(0, sql.IndexOf("WHERE") - 1);
也许这会更清楚
sql = sql.Replace(" WHERE", String.Empty);
此外,您的代码易受SQL注入攻击 - 您应该使用参数。
答案 1 :(得分:1)
我会使用system.Linq。
进行查询你可以这样做:
DataSet.Select(record => record.column == requiredvalue);
这将返回一个IQueryable,您可以在其上应用更多条件。 只有在开始使用结果时才会执行查询。
例如:
var result = DataSet.Select(...);
List list = result.ToList();
查询的执行发生在ToList();
上