无法填充 DataSet 但 MySqlCommand 工作正常

Cant fill DataSet but MySqlCommand works properly

所以我无法填充数据集。我得到以下异常:

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) (Microsoft SQL Server, Error: 1326)

但是使用相同的 ConnectionString 我可以使用 MySqlCommand class.

执行查询

这里有效:

var con = ConfigurationManager.ConnectionStrings["conString"];
_helper = new MySqlHelper(con.ConnectionString);
string query = "SELECT Bezeichnung FROM stationen";
var reader = _helper.ExecuteReader(query);
while(reader.Read())
{
    //do something
}

但是如果我使用数据集,我在尝试填充数据集时会收到错误消息

var con = ConfigurationManager.ConnectionStrings["conString"];
string query = "SELECT Bezeichnung FROM stationen";

using (SqlDataAdapter adapter = new SqlDataAdapter(query, con.ConnectionString))
{
    var dataset = new U2ZFDataSet();
    adapter.Fill(dataset, "stationen");
}

我做错了什么?为什么 DataSet 无法正常工作?

此外,这是 MySqlHelpter 代码:

private MySqlConnection _connection;

public MySqlHelper(string connectionString)
{
    try
    {
        _connection = new MySqlConnection(connectionString);
        _connection.Open();
    }
    catch (Exception ex)
    {
        if (_connection != null)
        {
            _connection.Dispose();
            _connection = null;
        }

        throw new Exception(connectionString, ex);
    }
}

public MySqlDataReader ExecuteReader(string sqlString)
{
    try
    {
        if (_connection == null || _connection.State != System.Data.ConnectionState.Open)
            throw new Exception("Connection closed");

        using (MySqlCommand command = new MySqlCommand(sqlString, _connection))
        {
            return command.ExecuteReader();
        }
    }
    catch (Exception ex)
    {
        throw new Exception(sqlString, ex);
    }
}

您应该在使用 SqlDataAdapter 之前打开连接。在第一个示例中,您使用了帮助器,它会为您执行此操作,但在第二个示例中,您不再使用该帮助器。

var con = ConfigurationManager.ConnectionStrings["conString"];
string query = "SELECT Bezeichnung FROM stationen";

con.Open();

using (SqlDataAdapter adapter = new SqlDataAdapter(query, con.ConnectionString))
{
    var dataset = new U2ZFDataSet();
    adapter.Fill(dataset, "stationen");
}

con.Close() -- do not forget to close it as well

检查这个例子here

如果您将连接开口包装在 try-catch 块中会更好,就像您在助手 class.

中所做的那样