【发布时间】:2019-04-08 09:42:57
【问题描述】:
我需要将从 C# Windows 窗体创建的连续整数列表与整数数据库表进行比较,指示是否存在重复项。
我有一个可用的版本,如下所示,但我假设它可能是执行此操作的效率最低的方法 - 将 C# 列表与数据库表中的每个整数一一进行比较。
我是否应该将数据库中的整数导入 C#,然后进行比较?或者有没有sql的查询方式:
如果列表 A 中的任何项目包含在列表 B 中,等等......而不是一一比较每个数字?
我已经看到很多关于仅在数据库中查找 1 项的意见,但我需要一种有效的方法来将有时 5,000 或更多的 C# 列表与最终可能包含数十万条记录的数据库表进行比较。
public static string VerifyManufacturingSerialOnly(int count, int beginning)
{
string duplicateSerials = "";
int currentSerial = beginning;
for (int i = 0; i < count; i++)
{
OleDbConnection connection = BadgeDatabaseDB.GetConnection();
string checkStatement
= "SELECT * "
+ "FROM SerialNumbersMFG "
+ "WHERE SerialNumber = @CurrentSerial";
OleDbCommand command =
new OleDbCommand(checkStatement, connection);
command.Parameters.AddWithValue("@CurrentSerial", currentSerial);
try
{
connection.Open();
OleDbDataReader dataReader =
command.ExecuteReader(CommandBehavior.SingleRow);
if (dataReader.Read())
{
duplicateSerials +=
"Serial # " +
currentSerial +
" already exists in order # " +
dataReader["OrderNumber"].ToString() + "\n";
}
else { }
}
catch (OleDbException ex)
{
throw ex;
}
finally
{
connection.Close();
}
currentSerial++;
i++;
}
return duplicateSerials;
【问题讨论】:
-
为什么不
Where SerialNumber IN YourCommaDelimitedListofNumbers?这样您就可以从数据库中返回所有匹配的数字(已经存在)。此外,除非您打算使用所有返回的列,否则您不应该Select *。选择要使用的内容。