C# ODBC 在 IN() 查询中使用参数
C# 新手,尝试将数组放入 IN() SQL 语句中。 换句话说,执行类似以下的查询:
SELECT * FROM table WHERE some IN( [array_elem_1], [array_elem_2] ... )
在 PHP/MySQL 中相当容易做到:
mysql_query('SELECT * FROM table WHERE something IN("' . implode('","', array_map('mysql_real_escape_string', $values)) .'")');
但最好用 C#/ODBC 计算:
using (OdbcCommand cmd = new OdbcCommand("SELECT * FROM table WHERE something IN (" + String.Join(",", Enumerable.Repeat("?", values.Count)) + ")", conn))
{
foreach (var kvp in values)
{
var param = cmd.CreateParameter();
param.Value = kvp.Key;
cmd.Parameters.Add(param);
}
cmd.ExecuteReader();
}
有吗也许有一个更好的方法来做到这一点,而不需要那么多代码? 谢谢!
New to C#, trying to put an array into an IN() SQL statement.
In other words, perform a query something like:
SELECT * FROM table WHERE something IN( [array_elem_1], [array_elem_2] ... )
Fairly easy to do in PHP/MySQL:
mysql_query('SELECT * FROM table WHERE something IN("' . implode('","', array_map('mysql_real_escape_string', $values)) .'")');
But best I could figure with C#/ODBC:
using (OdbcCommand cmd = new OdbcCommand("SELECT * FROM table WHERE something IN (" + String.Join(",", Enumerable.Repeat("?", values.Count)) + ")", conn))
{
foreach (var kvp in values)
{
var param = cmd.CreateParameter();
param.Value = kvp.Key;
cmd.Parameters.Add(param);
}
cmd.ExecuteReader();
}
Is there perhaps a nicer way to do this without so much code?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论