我正在用 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/