我有一个 sSQl 语句,我想根据下拉列表的选定值从数据库中选择值。 这是我的代码。
string sSQL = "";
sSQL = ("Select * From tbl_TripPrefixDestination Where Country like {0}", ddlCountrySelect.SelectedItem.Text);
sSQL += "";
sSQL += "";
OpenConnection(conn);
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand(sSQL, conn);
对我来说这似乎是正确的方法,但我仍然会出错。谁能帮帮我吗? (别介意
请您参考如下方法:
在最简单的层面上,您可能需要:
sSQL = String.Format("Select * From tbl_TripPrefixDestination Where Country like '%{0}%'", ddlCountrySelect.SelectedItem.Text);
如果您正在进行通配符搜索或
sSQL = String.Format("Select * From tbl_TripPrefixDestination Where Country = '{0}'", ddlCountrySelect.SelectedItem.Text);
对于完全匹配。
但是你应该看看 SqlParameter 对象:
sSQL = "Select * From tbl_TripPrefixDestination Where Country = @Country";
...
SqlParameter param = new SqlParameter("@Country", ddlCountrySelect.SelectedItem.Text);
SqlCommand cmd = new SqlCommand(sSQL, conn);
cmd.Parameters.Add(param);
正如 PaulG 所说,使用 sqlparameter 的一个(重要)原因是您的数据库将自动转义数据以防止注入(inject)攻击 - 另一个是提高性能。 http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/
