我需要检索存储在数千个项目的数据库中的信息.如果我通过这种方式逐个进行,则需要花费大量时间(tac是一个8个字符的字符串):
string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=DataBase\IMEIDB.accdb";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
connection.Open();
using (OleDbCommand command = connection.CreateCommand())
{
OleDbDataReader reader;
command.CommandText = "SELECT TAC, Name, Model, Year, Manufacturer, LTE FROM Terminales WHERE TAC = @tac";
command.Parameters.AddWithValue("@tac", tac);
reader = command.ExecuteReader();
while (reader.Read())
{
ulong tac = Convert.ToUInt64(reader.GetString(0));
if (this.DiccionarioTerminales.ContainsKey(tac))
{
DiccionarioTerminales[tac].inDB = true;
DiccionarioTerminales[tac].Name = reader.GetValue(1).ToString();
DiccionarioTerminales[tac].Manufacturer = reader.GetValue(2).ToString();
DiccionarioTerminales[tac].Model = reader.GetValue(3).ToString();
DiccionarioTerminales[tac].Year = reader.GetValue(4).ToString();
DiccionarioTerminales[tac].LTE = reader.GetValue(5).ToString();
}
}
command.Dispose();
}
connection.Dispose();
}
Run Code Online (Sandbox Code Playgroud)
它运行良好(我知道我必须使用ExecuteNonQuery()它,如果它只有一个记录,但这个例子只是一个测试),但如果我尝试将tac 10分组10(现在tac是一个字符串'xxxxxxxx','xxxxxxxx','xxxxxxxx','xxxxxxxx'...),我的代码中的下一个更改...
OleDbDataReader reader;
command.CommandText = "SELECT TAC, Name, Model, Year, Manufacturer, LTE FROM Terminales WHERE TAC IN (@tac)";
command.Parameters.AddWithValue("@tac", tac);
Run Code Online (Sandbox Code Playgroud)
它没有进入while循环,我不知道为什么......
有什么东西我缺少或者我可能需要使用另一种方法来检索这些数据?
编辑:根据SonerGönül答案更改格式
因为当你在IN子句中使用这个字符串时,它似乎是;
IN (xxxxxxxx,xxxxxxxx,xxxxxxxx,xxxxxxxx)
Run Code Online (Sandbox Code Playgroud)
但正确的语法应该是
IN ('xxxxxxxx','xxxxxxxx','xxxxxxxx','xxxxxxxx')
Run Code Online (Sandbox Code Playgroud)
这就是为什么它不起作用.一种解决方案可能是,您可以拆分字符串,,使用单引号格式化它们并,再次连接它们.
var str = "xxxxxxxx,xxxxxxxx,xxxxxxxx,xxxxxxxx";
var result = string.Join(",", str.Split(',').Select(s => string.Format("'{0}'", s)));
Run Code Online (Sandbox Code Playgroud)
result将是'xxxxxxxx','xxxxxxxx','xxxxxxxx','xxxxxxxx'你可以在你的IN条款中使用它;
...TAC IN (@tac)
Run Code Online (Sandbox Code Playgroud)
和
command.Parameters.AddWithValue("@tac", result);
Run Code Online (Sandbox Code Playgroud)
也不要AddWithValue尽可能多地使用.有时它可能会产生意想不到的惊人结果.使用Add方法重载来指定参数类型及其大小.
相关:参数化SQL IN子句
| 归档时间: |
|
| 查看次数: |
109 次 |
| 最近记录: |