C# MySql 获取行数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17285071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MySql get number of rows
提问by MTA
I try to get number of rows from a table with this :
我尝试从表中获取行数:
string commandLine = "SELECT COUNT(*) FROM client";
using (MySqlConnection connect = new MySqlConnection(connectionStringMySql))
using (MySqlCommand cmd = new MySqlCommand(commandLine, connect))
{
connect.Open();
int count = (int)cmd.ExecuteScalar();
return count;
}
And i get the exception:
我得到了例外:
Specified cast is not valid.
Any idea how i can fix it?
知道我该如何解决吗?
采纳答案by MDMalik
Try this
尝试这个
using (MySqlCommand cmd = new MySqlCommand(commandLine, connect))
{
connect.Open();
return Convert.ToInt32(cmd.ExecuteScalar());
}
回答by Fabian Bigler
using (MySqlCommand cmd = new MySqlCommand(commandLine, connect))
{
connect.Open();
return Convert.ToInt32(cmd.ExecuteScalar());
}
EDIT:Make also sure to handle exceptions in your code (E.g. if there is SQL Connection Error).
Also, if it's not a COUNT(*)the value returned by ExecuteScalar()can be null (!)
编辑:还要确保处理代码中的异常(例如,如果存在 SQL 连接错误)。此外,如果它不是,则COUNT(*)返回的值ExecuteScalar()可以为 null (!)
回答by Michael Knowles
If you wish to use the cast, you can use:
如果你想使用演员表,你可以使用:
long count = (long)cmd.ExecuteScalar();
As mentioned above, COUNT in MySql returns BIGINT, hence casting with an int fails.
如上所述,MySql 中的 COUNT 返回 BIGINT,因此使用 int 进行转换失败。

