我想创建类似if (reader["assignID"].count > 2)
的东西,然后发生一些事情。但我知道MySqlDataReader
没有计数功能。我还应该如何处理呢?
我要计算行数。
我的代码
try
{
string myConnectionString3;
myConnectionString3 = "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
MySqlConnection connection3 = new MySqlConnection(myConnectionString3);
MySqlCommand cmd3 = new MySqlCommand();
EncodingProvider ppp3;
ppp3 = CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(ppp3);
cmd3.CommandType = CommandType.Text;
string sqlStr2 = "Select assignID from assign where userId=@name";
cmd3.Parameters.AddWithValue("@name", txtValue.Text);
cmd3.CommandText = sqlStr2;
cmd3.Connection = connection3;
connection3.Open();
MySqlDataReader reader1 = cmd3.ExecuteReader();
if (reader1.HasRows)
{
while (reader1.Read())
{
if (reader1["assignID"].count > 2) //count rows if more than 2
{
txtAssignID1.Text += "Hello";
}
else
{
btnStart.IsEnabled = true;
string assignID = (reader1["assignID"].ToString());
txtAssignID1.Text += "Your exercise ID is: " + assignID;
}
}
}
else
{
txtAssignID1.Text += "You have not been assigned any exercise ID";
txtAssignID.IsEnabled = false;
}
connection3.Close();
}
catch (MySqlException)
{
}
答案 0 :(得分:2)
如果您想知道单个用户有多少个 assignID ,则应将其询问给数据库。将查询更改为
string sqlStr2 = "Select COUNT(assignID) as Totals from assign where userId=@name";
然后使用 ExecuteScalar 取回结果
int assignCount = 0;
// We need to check for nulls, because if the where condition doesn't
// match any userid then ExecuteScalar returns null.
object result = cmd3.ExecuteScalar();
if(result != null)
assignCount = Convert.ToInt32(result);
并删除所有数据读取器的内容。
如果您还需要知道AssignID的值,则应返回MySqlDataReader方法,但再次使用不同的查询
string sqlStr2 = @"Select assignID, COUNT(assignID) as Totals
from assign where userId=@name
GROUP BY assignID";
.....
MySqlDataReader reader1 = cmd3.ExecuteReader();
if (reader1.HasRows)
{
while (reader1.Read())
{
if ((int)reader1["Totals"] > 2)
{
// Not clear what you want to do if Totals > 2
txtAssignID1.Text += "Hello";
}
else
{
btnStart.IsEnabled = true;
string assignID = (reader1["assignID"].ToString());
txtAssignID1.Text += "Your exercise ID is: " + assignID;
}
}
}
else
{
txtAssignID1.Text += "You have not been assigned any exercise ID";
txtAssignID.IsEnabled = false;
}
答案 1 :(得分:0)
如果只需要知道计数是否大于2,则最好使用计数查询并执行GetScalar。这样,您仅检索必要的数据。