从数据库登录

时间:2013-06-05 15:43:13

标签: c# mysql winforms

基于本教程: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转换成String?

3 个答案:

答案 0 :(得分:1)

如何使用ExecuteScalar代替:

var pwd = command.ExecuteScalar() as string;

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

答案 1 :(得分:0)

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

应该找到你的字符串。

答案 2 :(得分:0)

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

    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
        }
    }