C# ASP.NET 使用 SqlConnection 连接 MySQL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18253120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:41:31  来源:igfitidea点击:

ASP.NET use SqlConnection connect MySQL

c#asp.netmysql.netsqlconnection

提问by John Walker

This is the connection string saved in web.config:

这是保存在的连接字符串web.config

<appSettings>
    <add key="conn" value="Driver={MySQL ODBC 5.1 Driver};server=127.0.0.1;uid=root;pwd=1234;database=gis_server;option=3"/>
    </appSettings>

This is the code to connect to the database:

这是连接数据库的代码:

protected bool CheckPasswordBySqlServer(string strEmail, string strPsw)
{
    if (strEmail.ToLower() == "admin")
    {
        return false;
    }
    string str = "select id,Rank,RankEnc,ParentUser,Company from tbl_User where userName=@UserName and password1=@password";
    private string strConn = ConfigurationManager.AppSettings["conn"].ToString();
    SqlConnection sqlConnection = new SqlConnection(strConn);
    bool flag = false;
    try
    {
        try
        {
            sqlConnection.Open();
            SqlCommand sqlCommand = new SqlCommand(str, sqlConnection);
            sqlCommand.Parameters.AddWithValue("UserName", strEmail);
            sqlCommand.Parameters.AddWithValue("Password", strPsw);
            SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
            if (!sqlDataReader.Read())
            {
                flag = false;
            }
            else
            {
                this.Session["UserName"] = strEmail;
                this.Session["Password"] = strPsw;
                this.Session["LoginType"] = "Group";
                this.Session["FullName"] = sqlDataReader["Company"].ToString();
                if (FormsAuthentication.HashPasswordForStoringInConfigFile(string.Concat(strEmail, (char)43, sqlDataReader["Rank"].ToString()).ToLower(), "MD5") != sqlDataReader["RankEnc"].ToString().Trim())
                {
                    flag = false;
                }
                this.Session["ClientID"] = sqlDataReader["id"].ToString();
                this.Session["MyLanguage"] = base.Request.Cookies["Language"].Value;
                this.Session["ParentUser"] = sqlDataReader["ParentUser"].ToString().Trim();
                this.Session["Rank"] = sqlDataReader["Rank"].ToString();
                this.Session["strConnection"] = this.strConn;
                flag = true;
            }
            sqlDataReader.Close();
        }
        catch (Exception exception)
        {
            this.SetlblInfoHtml(exception.Message);
        }
    }
    finally
    {
        sqlConnection.Close();
    }
    return flag;
}

But it fails to connect MySQL, with this return error:

但它无法连接 MySQL,并返回以下错误:

System.ArgumentException: Keyword not supported: 'driver'. at System.Data.Common.DbConnectionOptions.ParseInternal(Hashtable parsetable, String connectionString, Boolean buildChain, Hashtable synonyms, Boolean firstKey) at System.Data.Common.DbConnectionOptions..ctor(String connectionString, Hashtable synonyms, Boolean useOdbcRules) at System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) at System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) at System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(String connectionString, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) at System.Data.SqlClient.SqlConnection.ConnectionString_Set(String value) at System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) at System.Data.SqlClient.SqlConnection..ctor(String connectionString) at Source_LoginFrm.CheckPasswordBySqlServer(String strEmail, String strPsw) at Source_LoginFrm.btnLogin_Click(String strLang)

Is that possible SqlConnection to connect MySQL database?

是否可以使用 SqlConnection 连接 MySQL 数据库?

采纳答案by Darren

SqlConnectionis for SQL Server. You need MySqlConnection- this is not part of the .NET Framework, so you will have to download itand reference it in your project. You can then create a MySqlConnectionobject and connect to MySQL in your application:

SqlConnection用于 SQL Server。您需要MySqlConnection- 这不是 .NET Framework 的一部分,因此您必须下载它并在您的项目中引用它。然后,您可以MySqlConnection在应用程序中创建一个对象并连接到 MySQL:

MySqlConnection connection = new MySqlConnection(myConnString);

You will also have to use the MySqlCommandobject rather than the SqlCommandobject.

您还必须使用MySqlCommand对象而不是SqlCommand对象。

http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlconnection.html

http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlconnection.html

回答by Justin

Not that I know of, and even if it would, why would you want to? You are using a connection object specifically created for Microsoft SQL Server, so it wouldn't connect in the same fashion MySQL does.

我不知道,即使会,你为什么要?您正在使用专为 Microsoft SQL Server 创建的连接对象,因此它不会以 MySQL 那样的方式进行连接。

For accessing a MySQL database, you should use the MySQL .NET connector which you can find here.

要访问 MySQL 数据库,您应该使用 MySQL .NET 连接器,您可以在此处找到。

回答by Mahmoud Valizadeh

as Darren seid "SqlConnection is for SQL Server." you need to install MySql.Data from NuGet: mySql.Data

正如 Darren seid “SqlConnection 用于 SQL Server”。你需要从安装的NuGet MySql.Data: mySql.Data

also you can use Install-Package MySql.Datain your Package Manager Console

您也可以在包管理器控制台中使用Install-Package MySql.Data

then you can create MySqlConnection object and connect to your database:

然后您可以创建 MySqlConnection 对象并连接到您的数据库:

var cnn = new MySqlConnection("my Connection String");