[英]Error using C# to count the number of mysql database rows with specific string varibles in them and display them as int
The code I am writing is to check how many employees are going to lunch at the same time. 我正在编写的代码是要检查有多少员工同时要吃午餐。 The information is in a MySQL table named: "edata" in the column named: "Lunchtime", and are stored as a string such as "4:00pm-5:00pm".
该信息位于名为“ Lunchtime”的列中的名为“ edata”的MySQL表中,并以字符串形式存储,例如“ 4:00 pm-5:00pm”。
Name | Lunchtime
------------------------
Paul 4:00pm-5:00pm
Mike 4:00pm-5:00pm
Aaron 1:00pm-2:00pm
The ultimate goal is to count the number of shifts that are chosen by the "lunchTimes.Text" variable and display how many employees selected the shift as an int named: "count". 最终目标是计算“ lunchTimes.Text”变量选择的轮班数量,并显示多少员工选择了该轮班作为名为“ count”的int。
ie Program user selects the "4:00pm-5:00pm" option, and the program returns "2" since 2 employees have selected that time slot. 即,程序用户选择“ 4:00 pm-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);
Currently I am getting this error: 目前,我收到此错误:
"An unhandled exception of type 'System.InvalidCastException' occurred in First_cSharp_App.exe Additional information: Specified cast is not valid." “在First_cSharp_App.exe中发生了类型为'System.InvalidCastException'的未处理异常。附加信息:指定的强制转换无效。”
At this line: 在这一行:
Int32 count = (Int32)cmdDataBase.ExecuteScalar();
I'm new to this so I apologize for any confusion. 我对此并不陌生,因此给您带来的任何困惑我深表歉意。
This is because ExecuteScalar returns object
which couldn't explicitly converted to Int32
at Runtime. 这是因为ExecuteScalar返回的
object
在运行时无法明确转换为Int32
。
The proper way will be doing the following: 正确的方法是执行以下操作:
int count = (int)(cmdDataBase.ExecuteScalar());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.