C# mysql 查询if语句

标签 c# mysql sql

所以我尝试创建一个简单的按钮来决定您是管理员还是用户。

但我无法让它正常工作。我已连接到 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/

相关文章:

php - mysql 选择随机用户,但投票较低的用户有更多机会

sql - 这可以用单个 SQL 查询来完成吗

c# - 为什么 Visual Studio Windows 窗体设计器代码不会导致内存泄漏?

c# - 获取 Unity 中的预制件文件位置

c# - "interface based programming"到底是什么?

c# - 无法正确连接字符串

c# - 使用 Facebook API 编辑帖子返回 OAuthException #100

php - Codeigniter mysql 按位运算符

c# - 如何使用 Entity Framework 获取列的最大值?

sql - 获取相关表中每行的前 5 行