如何使用C#连接到Mysql? [英] How to connect to Mysql using C#?

查看:81
本文介绍了如何使用C#连接到Mysql?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是C#的初学者.我将XAMPP服务器用于MySQL数据库和Visual C#2010.然后在phpMyAdmin中创建了一个名为"testdb"的数据库和一个名为"login"的表.我已经在表中插入了用户名和密码.我正在做一个简单的WinForm登录,在其中我输入了两个用于输入用户名和密码的文本框和一个按钮.我已完成代码,没有编译器错误.但是我曾一线烦恼.它显示无法连接到任何指定的MySQL主机".我将MySql.Data添加到引用中.我要在登录时获取数据库表中的数据.然后授权用户,或者如果用户不匹配,则会提示错误消息.

I'm just a beginner in C#. I'm using XAMPP server for MySQL database and Visual C# 2010. Then I have created a database named "testdb" in phpMyAdmin and a table named "login". I have inserted my username and password in the table. I'm doing a simple WinForm login where I made two text boxes for username and password and a button. I have my codes done and there's no compiler error. But I had troubled in one line. It says "Unable to connect to any of the specified MySQL hosts". I added MySql.Data to my references. I want to fetch the data in the database table when I'm going to log in. Then authorize the user or if not matched, it will prompt an error message.

这是我的代码:

using MySql.Data.MySqlClient; 

public bool Login(string username, string password)
{
    MySqlConnection con = new MySqlConnection("host=localhost;username…");
    MySqlCommand cmd = new MySqlCommand("SELECT * FROM login WHERE username='" +
                                      username + "' AND password='" + password + "';");

    cmd.Connection = con;

    con.Open(); // This is the line producing the error.

    MySqlDataReader reader = cmd.ExecuteReader();

    if (reader.Read() != false)
    {    
        if (reader.IsDBNull(0) == true)
        {
            cmd.Connection.Close();
            reader.Dispose();
            cmd.Dispose();
            return false;
        }    
        else
        {
            cmd.Connection.Close();
            reader.Dispose();
            cmd.Dispose();
            return true;
        }    
    }    
    else
    {
        return false;
    }    
}

*我希望收到您的反馈. :)

*I hope for your your feedback. :)

推荐答案

您的直接问题可能是连接字符串不正确或数据库服务器不可用.连接字符串应该是这样的

Your immediate problem is probably either an incorrect connection string or the database server is not available. The connection string should be something like this

Server=localhost;Database=testdb;Uid=<username>;Pwd=<password>;

<username><password>替换为您的实际值.

with <username> and <password> replaced with your actual values.

此外,您的代码中有几个问题,如果打算将其变成生产代码,甚至可能只是为了学习一些东西的玩具项目,也应该对它们进行调查.该列表顺序特殊,可能不完整.

Besides that your code has several issues and you should definitely look into them if this is intended to become production code and probably even if this is just a toy project to learn something. The list is in particular order and may not be comprehensive.

  1. 请勿对连接字符串进行硬编码. 将其移至配置文件.
  2. 请勿在配置文件或源代码中包含纯文本密码.有各种解决方案,例如 Windows身份验证,证书 .aspx"rel =" nofollow noreferrer> Windows数据保护API .
  3. 不要仅通过调用IDisposable.Dispose()来处置IDisposable实例. 即使在出现异常的情况下,也要使用using语句来释放资源.
  4. 请勿使用字符串操作技术来构建SQL语句. 请改为使用SqlParameter来防止SQL注入攻击
  5. 请勿在数据库中存储纯文本密码. 至少至少存储密码的哈希值并使用慢速哈希函数,而不是MD5或SHA的成员家庭.
  6. 您可以使用 IDbCommand.ExecuteScalar 检索标量结果,并避免使用数据读取器.
  7. 将布尔值与truefalse进行比较是多余的,只会给代码增加噪音.可以使用if (reader.IsDBNull(0))代替if (reader.IsDBNull(0) == true). if (reader.Read() != false)等同于if (reader.Read() == true),因此也等同于if (reader.Read()).
  8. 使用像实体框架这样的O/R映射器是通常比在SQL命令级别上与数据库交互更受欢迎.
  1. Do not hard code your connection string. Instead move it to a configuration file.
  2. Do not include plain text passwords in configuration files or source code. There are various solutions like windows authentication, certificates or passwords protected by the Windows Data Protection API.
  3. Do not just dispose IDisposable instances by calling IDisposable.Dispose(). Instead use the using statement to release resources even in the case of exceptions.
  4. Do not build SQL statements using string manipulation techniques. Instead use SqlParameter to prevent SQL injection attacks.
  5. Do not store plain text passwords in a database. Instead at least store salted hashes of the passwords and use a slow hash function, not MD5 or a member of the SHA family.
  6. You can use IDbCommand.ExecuteScalar to retrieve a scalar result and avoid using a data reader.
  7. Comparing a boolean value with true or false is redundant and just adds noise to your code. Instead of if (reader.IsDBNull(0) == true) you can just use if (reader.IsDBNull(0)). The same holds for if (reader.Read() != false) what is equivalent to if (reader.Read() == true) and therefore also if (reader.Read()).
  8. Using an O/R mapper like the Entity Framework is usually preferred over interacting with the database on the level of SQL commands.

这篇关于如何使用C#连接到Mysql?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆