[英]How would I go about creating a login form using a database for a check?
我有一個數據庫,其中有一個名為person
的表,其中有兩行稱為personID
和firstName
現在,我有一個帶有2個文本框的表單,要求提供ID和名字。
問題是,我不知道如何檢查數據庫(如果ID和firstName來自同一記錄),並且如果記錄匹配並且如果它們不僅僅給出錯誤標簽,則將您帶到另一種稱為admin
形式。
我希望對此有任何幫助,謝謝。
編輯:這是到目前為止的代碼, connection already open, connection must be open
錯誤
private void btnLoginScreen_Click(object sender, EventArgs e)
{
{
switch (dbAuth(txtAdminLogID.Text, txtAdminLogName.Text))
{
case true:
//Open Admin form
break;
case false:
//Show Errorlabel here
break;
case null:
//An error occured while fetching data
break;
default:
break;
}
}
}
public bool? dbAuth(string personID, string firstName)
{
try
{
MySqlCommand command = new MySqlCommand();
command.CommandText = "SELECT * FROM person";
MySqlDataReader Reader;
conn.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
if (Reader[0].ToString() == personID) //first check if the ID is equal
{
if (Reader[1].ToString() == firstName) //if ID is equal, check if firstName is equal
{
conn.Close();
return true;
}
}
}
conn.Close();
return false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
編輯:這是我的連接字符串:
string connstring = "server=localhost;user Id=root;database=collegesystem;Convert Zero Datetime=True ";
MySqlConnection conn;
這就是我要走的樣子(使用MySQL-Connector):
public bool? Authenticate(string personID, string firstName)
{
try
{
MySqlCommand command = connection.CreateCommand();
command.CommandText = "SELECT * FROM yourTable";
MySqlDataReader Reader;
connection.Open();
Reader = command.ExecuteReader();
while (Reader.Read())
{
if (Reader[0].ToString() == personID) //first check if the ID is equal
{
if (Reader[1].ToString() == firstName) //if ID is equal, check if firstName is equal
{
connection.Close();
return true;
}
}
}
connection.Close();
return false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
在您的表單中,登錄按鈕所在的位置使用以下代碼:
private void MySQL_Auth_button_Click(object sender, EventArgs e)
{
switch (dbAuth.AuthenticatePlain(personID_textBox.Text, firstName_textBox.Text))
{
case true:
//Open Admin form
break;
case false:
//Show Errorlabel here
break;
case null:
//An error occured while fetching data
break;
default:
break;
}
}
“這是您必須在“登錄”按鈕后面編寫的代碼
SqlConnection CN =新的SqlConnection(ConnectionString);
string query= "Select * from tblUsers Where (user_id=@id AND user_password=@pwd)";
CN.Open();
SqlCommand myCommand = new SqlCommand(txt, CN);
myCommand.Parameters.Add(new SqlParameter("id", SqlDbType.NVarChar)).Value = this.txtUserID.Text;
myCommand.Parameters.Add(new SqlParameter("pwd", SqlDbType.NVarChar)).Value = this.txtPassword.Text;
SqlDataReader myReader;
myReader = myCommand.ExecuteReader();
myReader.Read();
if (myReader.HasRows)
{
CN.Close();
AdminForm mf = new AdminForm();
mf.Show();
this.Hide();
}
else
{
MessageBox.Show("Invalid User Name or Password", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.