[英]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.