从数据库登录

本文关键字:登录 数据库 | 更新日期: 2023-09-27 18:16:58

基于本教程:http://www.codeproject.com/Tips/423233/How-to-Connect-to-MySQL-Using-Csharp

我有一张桌子

CREATE TABLE Employee {
ID int,
Name varchar(20),
Password varchar(20),
}

现在我有了一个新的

INSERT INTO employee(ID, Name, Password) VALUES (001, 'John', 'abc')

以下是我如何尝试从TextBox 中获取ID中的字符串形式接收密码

MySqlConnection connection = new MySqlConnection("Server=localhost; Database=sad - final project; Uid=root; Pwd=");
        connection.Open();
        try
        {
            MySqlCommand command = connection.CreateCommand();
            command.CommandText = "SELECT Password FROM  employee WHERE ID = '" + Input_ID + "'";
            MySqlDataAdapter adapter = new MySqlDataAdapter(command);
            DataSet myDataSet = new DataSet();
            adapter.Fill(myDataSet);
        } catch blablabla

如果Input_ID为001,我希望从myDataSet中获得一个包含密码(为"abc"(的字符串,以便将其与另一个文本框中的密码输入进行比较。如何将此myDataSet转换为字符串?

从数据库登录

不如使用ExecuteScalar

var pwd = command.ExecuteScalar() as string;

现在你有了string。我不会在这个答案中用你的代码来解决安全问题,它们是巨大的。

DataRow row = myDataSet.Tables[0].Row[0];
string password = row["Password"];

应该能帮你找到线索。

您应该使用ExecuteScalar来获取字符串的密码。此外,您应该使用using关键字来确保正确处理您的连接/命令。此外,您需要在选择中使用参数来防止注入。

    using (MySqlConnection connection = new MySqlConnection("Server=localhost; Database=sad - final project; Uid=root; Pwd=");
    using (MySqlCommand command = new MySqlCommand("SELECT password FROM employee WHERE ID = @UserId", connection)
    {
        try
        {
            connection.Open();
            command.Parameters.AddWithValue("@UserId", Input_ID); 
            var pwd = command.ExecuteScalar() as string;
            //Do something with the stored password.
            //Consider encryption and other security concerns when working with passwords.
        } 
        catch (Exception ex)
        {
            //handle your exceptions
        }
    }