所以我尝试创建一个简单的按钮来决定您是管理员还是用户。
但我无法让它正常工作。我已连接到 MySQL 数据库,但是当我使用管理员/用户帐户(存储在数据库中)单击按钮时,我得到:
"you are an admin"
所以我想我在某个地方犯了错误,但看不到哪里:
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection cn = new MySqlConnection("Server=;Database=;Uid=;Pwd=;");
MySqlCommand cmd = new MySqlCommand("SELECT usertype FROM table1 ", cn);
cmd.Parameters.AddWithValue("usertype", usertype.Text);
cn.Open();
string usertype123 = cmd.ExecuteScalar()?.ToString();
if (usertype123 == "admin")
{
MessageBox.Show("you are an admin");
}
else
{
MessageBox.Show("You are an user ");
}
cn.Close();
}
最佳答案
如果您没有在 sql 命令中添加 WHERE 语句,您将始终从数据库引擎返回的第一行的第一列中检索值。您应该将代码更改为这样的内容
private void button1_Click(object sender, EventArgs e)
{
// I assume you have a field named UserID as the primary key of your table1
string sqlCmd = @"SELECT usertype FROM table1 WHERE UserID=@id";
using(MySqlConnection cn = new MySqlConnection("....."))
using(MySqlCommand cmd = new MySqlCommand(sqlCmd, cn))
{
cmd.Parameters.Add("@id", MySqlDbType.Int32).Value = currentUserid;
cn.Open();
string usertype123 = cmd.ExecuteScalar()?.ToString();
if (usertype123 == "admin")
{
MessageBox.Show("you are an admin");
}
else
{
MessageBox.Show("You are an user ");
}
}
}
现在的问题是如何定义变量currentUserId,这是您在用户登录时需要检索的内容,并在类级别保存以便在需要时重用。另请注意,连接器是一次性元素,因此您需要在使用完它们后立即将其丢弃。 using 语句有助于做到这一点
关于C# mysql 查询if语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55068414/