Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用C#计算包含特定字符串变量的mysql数据库行数并将其显示为int时出错_C#_Mysql - Fatal编程技术网

使用C#计算包含特定字符串变量的mysql数据库行数并将其显示为int时出错

使用C#计算包含特定字符串变量的mysql数据库行数并将其显示为int时出错,c#,mysql,C#,Mysql,我写的代码是检查有多少员工同时吃午饭。信息位于名为“午餐时间”列中名为“edata”的MySQL表中,并以字符串形式存储,如“4:00pm-5:00pm” 最终目标是统计“午餐时间.文本”变量选择的班次数,并显示有多少员工选择了名为“count”的整数形式的班次 i、 e.程序用户选择“4:00pm-5:00pm”选项,程序返回“2”,因为有2名员工选择了该时间段 private void select_btn_Click(object sender, EventArgs e) {

我写的代码是检查有多少员工同时吃午饭。信息位于名为“午餐时间”列中名为“edata”的MySQL表中,并以字符串形式存储,如“4:00pm-5:00pm”

最终目标是统计“午餐时间.文本”变量选择的班次数,并显示有多少员工选择了名为“count”的整数形式的班次

i、 e.程序用户选择“4:00pm-5:00pm”选项,程序返回“2”,因为有2名员工选择了该时间段

private void select_btn_Click(object sender, EventArgs e)
    {

        shiftLunch = lunchTimes.Text;

        string constring = "datasource=127.0.0.1;port=3306;username=root;password=password";
        string Query = "select count(Lunchtime) from database.edata where Lunchtime= '"+shiftLunch+"';";

        MySqlConnection conDataBase = new MySqlConnection(constring);
        MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);

        conDataBase.Open();
        Int32 count = (Int32)cmdDataBase.ExecuteScalar();


        Console.WriteLine(count);
目前我遇到以下错误:

“第一个\u cSharp\u App.exe中发生类型为“System.InvalidCastException”的未处理异常 其他信息:指定的强制转换无效。“

在这一行:

Int32 count = (Int32)cmdDataBase.ExecuteScalar();
我是新手,所以我为任何困惑道歉。

这是因为返回的
对象在运行时无法显式转换为
Int32

正确的方法是执行以下操作:

int count = (int)(cmdDataBase.ExecuteScalar());

你确定你的结果会回来吗。如果找不到行,ExecuteScalar我相信将返回null。该查询连接看起来像sql注入机会。没问题。。请随意投票并接受答案。我更喜欢这样的东西:int.Parse(cmdDataBase.ExecuteScalar().ToString());选择转换的原因是什么?
int count=(int)(cmdDataBase.ExecuteScalar())这应该可以,如果他只是返回一个count@cFrozenDeath,谢谢,但我不是在评论操作码,在这种情况下,我选择帮助他通过这个障碍。我知道你是,但为什么不一次帮助他两次呢?我的意思是,最好尽早习惯最佳实践。。。
int count = (int)(cmdDataBase.ExecuteScalar());