[英]How to add images to database and then display them in datagridview using C#?
[英]Error using C# to count the number of mysql database rows with specific string varibles in them and display them as int
我正在編寫的代碼是要檢查有多少員工同時要吃午餐。 該信息位於名為“ 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
最終目標是計算“ lunchTimes.Text”變量選擇的輪班數量,並顯示多少員工選擇了該輪班作為名為“ count”的int。
即,程序用戶選擇“ 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);
目前,我收到此錯誤:
“在First_cSharp_App.exe中發生了類型為'System.InvalidCastException'的未處理異常。附加信息:指定的強制轉換無效。”
在這一行:
Int32 count = (Int32)cmdDataBase.ExecuteScalar();
我對此並不陌生,因此給您帶來的任何困惑我深表歉意。
這是因為ExecuteScalar返回的object
在運行時無法明確轉換為Int32
。
正確的方法是執行以下操作:
int count = (int)(cmdDataBase.ExecuteScalar());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.