通过asp.net连接到mysql数据库

时间:2018-06-07 17:53:25

标签: c# mysql asp.net

我正在尝试连接到asp.net中的MySQL数据库(我猜是那个noob; p)

我在这件事上真的很新(卑鄙的asp)

我正在使用VS 2013 Pro,MySQL Server 8.0.11,我已经为visual studio 1.2.8安装了Connector / Net和mysql

在“服务器资源管理器”选项卡中,我与db有连接,我看到了我的表,测试成功(用于MySQL的.NET Framework数据提供程序和MySQL数据库(MySQL数据提供程序)) enter image description here

但我无法通过代码(?)

获得连接

当我尝试这个时:

protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            using (OdbcConnection connection = new OdbcConnection(ConfigurationManager.ConnectionStrings["MySQL"].ConnectionString))
            {
                connection.Open();
                using (OdbcCommand command = new OdbcCommand("SELECT imie FROM pracownicy", connection))
                using (OdbcDataReader dr = command.ExecuteReader())
                {
                    while (dr.Read())
                        Response.Write(dr["imie"].ToString() + "<br />");
                    dr.Close();
                }
                connection.Close();
            }
        }
        catch (Exception ex)
        {
            Response.Write("An error occured: " + ex.Message);
        }

    }

这是web.config

的一部分
<connectionStrings>
<add name="MySQL" connectionString="Driver={MySQL ODBC 8.0.11 Driver};server=localhost;uid=marcin;pwd=pass;database=test" />

我正在得到像这样的东西: 发生错误:错误[IM002] [Microsoft] [ODBC驱动程序管理器]无法设置名称数据源,并且未提供默认驱动程序

我也试试这个:

添加了对MySql.Data.dll的引用

和代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using MySql.Data.MySqlClient;

namespace WebApplication1
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            MySqlConnection con = new MySqlConnection("server=localhost;user id=marcin;persistsecurityinfo=True;database=test;password=pass");
        }
    }
}

只有我得到

Warning     The primary reference "MySql.Data, Version=8.0.11.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d, processorArchitecture=MSIL" could not be resolved because it was built against the ".NETFramework,Version=v4.5.2" framework. This is a higher version than the currently targeted framework ".NETFramework,Version=v4.5".

Error   The type or namespace name 'MySql' could not be found (are you missing a using directive or an assembly reference?)

我做错了什么?

1 个答案:

答案 0 :(得分:0)

最简单的方法是将目标增加到.NET 4.5.2或更高版本。您正在尝试使用针对4.5.2构建的MySQL dll,而您仅使用4.5.0。

相关问题