无法从'system.data.sqlclient.sqlconnection'转换为'string' [英] Cannot convert from 'system.data.sqlclient.sqlconnection' to 'string'

查看:669
本文介绍了无法从'system.data.sqlclient.sqlconnection'转换为'string'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我以字符串格式返回连接字符串时,我收到一条错误,指出无法从'System.Data.SqlClient.SqlConnection'转换为'String'



任何人都可以解释我



我尝试过:



When i am returning the connectionstring in string format i am getting an error saying Cannot Convert from 'System.Data.SqlClient.SqlConnection' to 'String'

Can anyone explain me

What I have tried:

public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
    if (connectionString == null || connectionString.Length == 0) throw new ArgumentNullException("connectionString");

    // Create & open a SqlConnection, and dispose of it after we are done
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();

        // Call the overload that takes a connection in place of the connection string
        return ExecuteNonQuery(connection, commandType, commandText, commandParameters);
    }
}

推荐答案

为什么递归调用相同的方法?你在 ExecuteNonQuery 方法内并再次调用它。



你打算打电话给 ExecoteNonQuery 命令方法



Why do you call the same method recursively? You're inside ExecuteNonQuery method and calling it again.

Did you intend to call the ExecoteNonQuery method of the command

...
connection.Open();
SqlCommand command = new SqlCommand(commandText, connection);
command.Connection.Open();
command.ExecuteNonQuery();
...


我把它打成了我的头顶,所以可能需要一些细微的调整,但这是一种更正确的方法要做到这一点。



I typed this off the top of my head, so it might need some minor tweaking, but this is a more correct way to do this.

public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params SqlParameter[] commandParameters)
{
    int result = 0;
    if (string.IsNullOrEmpty(connectionString)
    {
        throw new ArgumentNullException("connectionString");
    }

    try
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            using SqlCommand cmd = new SqlCommand(commandText, conn))
            { 
                cmd.CommandType = commandType;
                cmd.Parameters.AddRange(commandParameters);
                result = cmd.ExecuteNonQuery();
            }
        }
    }
    catch (Exception ex)
    {
       // handle the exception here
    }
    return result;
}


这篇关于无法从'system.data.sqlclient.sqlconnection'转换为'string'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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