我的應用程式從登錄選單開始,用戶提供他的登錄憑據,然后比較密碼(散列)的程序繼續進行,如果一切正常則登錄,如果出現錯誤則錯誤處理程式啟動。
我的問題是,有沒有辦法檢查目標表是否為空,就像其中沒有任何型別的資料一樣(只是資料庫中的骨架表)。因為我不愿意 150 多名員工坐在桌子上,他們可能會離職、升職和被解雇……所以我想把它留給管理公司人力資源的管理員……
我使用了該Form_Activated事件但沒有任何改變,嘗試該Form_Initialize事件沒有運氣。我在這里做錯了什么?
我應該更改我的查詢嗎?我完全迷失在這里,因為我閱讀了數十種表格,而NON甚至接近了!
使用隨表單initialize事件提供的代碼不起作用。因為它會處理表單,而您無法解決問題,或者至少我不能!
try
{
using (MySqlConnection connection = Connect())
{
DataTable table = new DataTable("employee");
string checkuserexistance = "select count(uname) from employee";
MySqlCommand command = new MySqlCommand(checkuserexistance, connection);
using (MySqlDataReader reader = command.ExecuteReader())
{
if (reader.Read() && reader.FieldCount > 0 && reader.HasRows)
{
Form1_Load(sender, e);
reader.Close();
}
else
{
DialogResult dialog = MessageBox.Show("Can not sign in as the given user, would you like to add a user now?", "Empty Database", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dialog == DialogResult.Yes)
{
new Thread(() => new User_Managment().ShowDialog()).Start();
this.Close();
}
else
{
Application.Exit();
}
}
}
}
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message, "Error Connecting to Database!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
uj5u.com熱心網友回復:
您的邏輯當前正在檢查是否有任何行回傳:
MySqlCommand command = new MySqlCommand("select count(uname) from employee", connection);
using (MySqlDataReader reader = command.ExecuteReader())
{
if (reader.Read() && reader.FieldCount > 0 && reader.HasRows)
{
// OK
}
}
但是, aSELECT COUNT(...)始終回傳(至少)一行,因此您還需要通過讀取第零個結果列的值來檢查從該單行讀取的計數是否大于零。
MySqlCommand command = new MySqlCommand("select count(uname) from employee", connection);
using (MySqlDataReader reader = command.ExecuteReader())
{
if (reader.Read() && reader.FieldCount > 0 && reader.HasRows && reader.GetInt32(0) > 0)
{
// OK
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/338140.html
上一篇:如何替換LPTSTR的值?
下一篇:雙擊以管理員身份執行
