我目前正在处理一个 C# 项目,我正在尝试获取从 MySQL 数据读取器返回的行数。
我知道没有直接函数,所以我正在尝试编写自己的函数。在该函数中,我将 MySQLDataReader
对象传递给它,然后循环遍历 MySQL 数据读取器并递增一个计数器并返回计数器的值。
然后这似乎锁定了程序,我猜是因为我是 Reader.read()
在我得到计数后我已经到了最后。相反,我尝试创建阅读器的副本,然后遍历临时版本,但我得到了相同的结果。
下面是我执行查询和调用函数的代码。
string query = "SELECT * FROM reports, software, platforms, versions "
+ "WHERE EmailVerified = @verified AND reports.SoftwareID = software.id AND reports.PlatformID = platforms.id "
+ "AND reports.VersionID = versions.id AND BugReportAcceptedNotificationSent = @notificationSent";
using (MySqlCommand cmd = new MySqlCommand(query, db.conn))
{
cmd.Parameters.AddWithValue("@verified", "1");
cmd.Parameters.AddWithValue("@notificationSent", "0");
using (MySqlDataReader reader = cmd.ExecuteReader())
{
totalEmails = HelperClass.totalRowsInMySQLDataReader(reader);
while (reader.Read())
{
currentEmailCount++;
EmailNotifications emailNotification = new EmailNotifications(reader);
emailNotification.sendNewBugReportAfterVerificationEmail(currentEmailCount, totalEmails);
}
}
}
下面是我获取行数的函数
public static int totalRowsInMySQLDataReader(MySqlDataReader reader)
{
MySqlDataReader tempReader = reader;
ILibraryInterface library = GeneralTasks.returnBitsLibrary(Configuration.databaseSettings, Configuration.engineConfig.logFile);
string methodInfo = classDetails + MethodInfo.GetCurrentMethod().Name;
try
{
int count = 0;
while (tempReader.Read())
{
count++;
}
tempReader = null;
return count;
}
catch (Exception ex)
{
string error = string.Format("Failed to get total rows in MySQL Database. Exception: {0}", ex.Message);
library.logging(methodInfo, error);
library.setAlarm(error, CommonTasks.AlarmStatus.Medium, methodInfo);
return -1;
}
}
最佳答案
使用 DataTable
加载您的结果,例如
DataTable dt = new DataTable();
dt.Load(reader);
int numberOfResults = dt.Rows.Count;
然后您还可以遍历行以读取值,例如
foreach(DataRow dr in dt.Rows)
{
var value = dr["SomeResultingColumn"]
}
另一种选择是发出两个单独的 SQL 语句,但是您需要确保这两个语句都包含在具有 Serializable
隔离级别的事务中,这是确保记录不被插入在两个 SQL 语句的执行之间。
关于c# - 检查从 MySQL Data Reader 返回的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21837407/