【问题标题】:ASP.Net MySql select errorASP.Net MySql 选择错误
【发布时间】:2013-11-03 21:14:49
【问题描述】:

我在我的 asp.net 网站上运行此功能:

private static DataTable GetData(string query)
{
    string strConnString = "SERVER=localhost;DATABASE=database;UID=root;PASSWORD=123456789;";
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = query;
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataSet ds = new DataSet())
                {
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    return dt;
                }
            }
        }
    }
}

使用此查询:

"select * from Client where id='"+ customerId +"'"

我得到了这个例外:

System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

知道什么可以解决这个问题吗?

【问题讨论】:

  • 您可以使用 MySQLWorkbench 或 HeidiSQL 之类的程序连接到数据库吗?如果是这样,查询(当customerId被实际数据替换时)是否正确执行?
  • SqlConnection 用于连接 MS SQL Server,而不是 mysql
  • @IlyaBursov 然后你就可以写出答案了....
  • asp.net 代码是否与 SQL Server (localhost) 在同一台机器上运行?

标签: c# mysql asp.net .net


【解决方案1】:

连接Mysql,试试这个:

*添加Mysql.Data.dll,读取here

*在页面顶部添加这一行

using MySql.Data.MySqlClient;

试试这个编辑过的方法:

private static DataTable GetData(string query)
{
    string strConnString = "SERVER=localhost;DATABASE=database;UID=root;PASSWORD=123456789;";
    using (MySqlConnection con = new MySqlConnection(strConnString))
    {
        using (MySqlCommand cmd = new MySqlCommand())
        {
            cmd.CommandText = query;
            using (MySqlDataAdapter sda = new MySqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataSet ds = new DataSet())
                {
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    return dt;
                }
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2014-06-15
    • 1970-01-01
    • 2013-07-17
    • 2019-01-18
    • 2010-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多