C# 和 MySql 更改列变量

标签 c# mysql

我正在用 C# 制作 mysql 注册/登录系统。我可以用它注册并登录。 我正在通过以下方式验证帐户:

MySqlConnection conn = new MySqlConnection(db_creds);
            try { conn.Open(); }
            catch { throw new Exception("Can't access database"); }
            MySqlDataAdapter adapter;
            DataTable table = new DataTable();
            string query = "SELECT `Nickname`, `Password` FROM `" + db_table + "` WHERE `Nickname` = '" + nickname + "' AND `Password` = '" + password + "'";
            adapter = new MySqlDataAdapter(query, conn);
            adapter.Fill(table);
            conn.Close();
            if(table.Rows.Count <= 0)
            {
                return false;
            }
            else { return true; }

在昵称和密码之后,我有名为 active 的 varchar。我的问题是: 当用户成功登录时,如何将“active”(仅适用于该用户)更改为1?当注销时将其更改为 0?

最佳答案

要更改表中的单行,您需要获取它的 ID(该表的唯一标识符)。将此唯一列的名称设为 str_Id,然后检索特定用户名和密码的 ID。然后您可以根据这个唯一标识符更新事件状态。

给您的另一个重要建议是,不要使用这种类型的纯文本查询,这将为 SQL 注入(inject)打开一扇大门。所以我强烈建议您使用参数化查询,如下所示;

string query = "SELECT Nickname,str_Id  FROM your_table_name" +
               " WHERE Nickname =@nickname  AND Password = @password";
MySqlConnection con = new MySqlConnection();

// Creating parameterized command

MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.Add("@nickname", MySqlDbType.VarChar).Value = nickname;
cmd.Parameters.Add("@password", MySqlDbType.VarChar).Value = password;
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataTable table = new DataTable();

// Collect the details to a DataTable

adapter.Fill(table);
if (table.Rows.Count>0) // Means there is some record found
{
    // Get theUnique ID for the matching record
    string uniqueId = table.Rows[0]["str_Id"].ToString();

    // Update active state for that particular user
    query = "Update your_table_name set active='0' Where str_Id=@str_Id";
    cmd = new MySqlCommand(query, con);
    cmd.Parameters.Add("@str_Id", MySqlDbType.VarChar).Value = uniqueId;
    // Execute command here
}
else
{
    // Print message thet no user found
}

关于C# 和 MySql 更改列变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37908811/

相关文章:

MYSQL安装日期使用查询

c# - FindAsync 返回最近的 1000 个结果

c# - AppDomain.AppendPrivatePath 替代方案?

c# - .net 自定义配置如何不区分大小写地解析枚举 ConfigurationProperty

php - 在插入之前查询主值时跳过主键编号

mysql - 如何从一个表中获取另一个表中不存在的值?

c# - 如何为WinForm应用程序创建全局资源文件?

c# - 为什么这种扩展方法不起作用?

javascript - 显示SQL表上的搜索功能

php - 如何使用 jquery 和 ajax 查询 mysql 数据库?