Kal*_*exx 18 c# sql ado.net sqlcommand
我似乎对如何In使用a 执行语句感到困惑SqlParameter.到目前为止,我有以下代码:
cmd.CommandText = "Select dscr from system_settings where setting in @settings";
cmd.Connection = conn;
cmd.Parameters.Add(new SqlParameter("@settings", settingList));
reader = cmd.ExecuteReader();
Run Code Online (Sandbox Code Playgroud)
settingsList是一个List<string>.当cmd.ExecuteReader()被调用时,ArgumentException由于无法将a映射List<string>到"已知的提供者类型" ,我得到了.
如何(安全地)In使用SqlCommands 执行查询?
Mar*_*ers 25
你可以尝试这样的事情:
string sql = "SELECT dscr FROM system_settings WHERE setting IN ({0})";
string[] paramArray = settingList.Select((x, i) => "@settings" + i).ToArray();
cmd.CommandText = string.Format(sql, string.Join(",", paramArray));
for (int i = 0; i < settingList.Count; ++i)
{
cmd.Parameters.Add(new SqlParameter("@settings" + i, settingList[i]));
}
Run Code Online (Sandbox Code Playgroud)
您似乎试图传递一个多值参数,SQL语法不会按预期执行.您可能希望传递表值参数.
阅读:http://www.sommarskog.se/arrays-in-sql.html#iter-list-of-strings
具体来说:http://www.sommarskog.se/arrays-in-sql-2008.html#ListSqlDataRecord
private static void datatable_example() {
string [] custids = {"ALFKI", "BONAP", "CACTU", "FRANK"};
DataTable custid_list = new DataTable();
custid_list.Columns.Add("custid", typeof(String));
foreach (string custid in custids) {
DataRow dr = custid_list.NewRow();
dr["custid"] = custid;
custid_list.Rows.Add(dr);
}
using(SqlConnection cn = setup_connection()) {
using(SqlCommand cmd = cn.CreateCommand()) {
cmd.CommandText =
@"SELECT C.CustomerID, C.CompanyName
FROM Northwind.dbo.Customers C
WHERE C.CustomerID IN (SELECT id.custid FROM @custids id)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("@custids", SqlDbType.Structured);
cmd.Parameters["@custids"].Direction = ParameterDirection.Input;
cmd.Parameters["@custids"].TypeName = "custid_list_tbltype";
cmd.Parameters["@custids"].Value = custid_list;
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
using (DataSet ds = new DataSet()) {
da.Fill(ds);
PrintDataSet(ds);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)