0

基于本教程: 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')

这是我尝试从文本框获取的 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 转换为字符串?

4

3 回答 3

1

如何ExecuteScalar改用:

var pwd = command.ExecuteScalar() as string;

现在你有了string. 我不会在这个答案中解决您的代码的安全问题,它们很庞大。

于 2013-06-05T15:44:55.710 回答
0
DataRow row = myDataSet.Tables[0].Row[0];
string password = row["Password"];

应该给你字符串。

于 2013-06-05T15:50:53.867 回答
0

您应该使用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
        }
    }
于 2013-06-05T15:52:57.140 回答