[英]i want to be able to validate a login form with an id or username, while getting the data from mysql database using c#
I am working on a project, so I decided to try some CRUD operations so as to be able to manipulate my database.我正在做一个项目,所以我决定尝试一些 CRUD 操作,以便能够操纵我的数据库。
I already created a form to insert data into the database and it worked, but I am finding it difficult to create that of read .我已经创建了一个表单来将数据插入数据库并且它工作正常,但是我发现很难创建 read 。
public int login(string id, string name)
{
MySqlDataReader dr;
int i = 0;
try
{
string query = "SELECT * FROM `all_data` WHERE admin_ID=@id and admin_Name=@name;
open_conn();
MySqlCommand cmd = new MySqlCommand(query,conn);
cmd.Parameters.AddWithValue("@id", id);
cmd.Parameters.AddWithValue("@name",name);
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
return i;
}
This is where I got confused, as I want it to read from my database and check if it matches my inputs.这是我感到困惑的地方,因为我希望它从我的数据库中读取并检查它是否与我的输入匹配。 If it matches, then it should perform an action.. maybe show a MessageBox saying "login successful".
如果匹配,那么它应该执行一个操作.. 可能会显示一个消息框说“登录成功”。
First, don't build your query by concatenating the id and name directly.首先,不要通过直接连接 id 和 name 来构建查询。 This would introduce a SQL injection vulnerability.
这将引入 SQL 注入漏洞。
string query = "SELECT * FROM `all_data` WHERE admin_ID='"+id+ "' and admin_Name='"+name+"' ";
Instead, use a parameterized query.相反,使用参数化查询。
string query = "SELECT * FROM `all_data` WHERE admin_ID=@id and admin_Name=@name";
cmd.Parameters.AddWithValue("@id", id);
cmd.Parameters.AddWithValue("@name",name);
Next, we just need to check if a record matches the inputs.接下来,我们只需要检查记录是否与输入匹配。 Thus, we can change the query to below to see how many records match.
因此,我们可以将查询更改为下面以查看匹配的记录数。
string query = "SELECT COUNT(*) FROM `all_data` WHERE admin_ID=@id and admin_Name=@name";
Finally, instead of ExecuteReader() we can use ExecuteScalar() to get the count.最后,我们可以使用 ExecuteScalar() 来代替 ExecuteReader() 来获取计数。 If the count is greater than 0, we know that there was a successful match.
如果计数大于 0,我们就知道匹配成功。
int matchingRecords = (int).ExecuteScalar();
if (matchingRecords > 0) {
// Logic for successful match
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.