【问题标题】:object reference not set to an instance of an object in dll对象引用未设置为 dll 中对象的实例
【发布时间】:2012-11-16 12:52:57
【问题描述】:

我在我的应用程序中编写了这个方法,它工作正常。我决定为它创建一个 DLL 文件。 但是同样的方法给了我错误object reference not set to an instance of an object in dll。 代码是

public void Try(string conStr, string storedProcedure)
    {

        try
        {

            //create a connection string
            sqlCon = new SqlConnection(conStr);

            // create command
            sqlCmd = new SqlCommand(sqlCmd.CommandText, sqlCon);

            //add command type
            sqlCmd.CommandType = CommandType.StoredProcedure;

            // add the stored procedure name
            sqlCmd.CommandText = storedProcedure;

            //Open connection
            sqlCon.Open();

            // Execute transaction
            sqlCmd.ExecuteNonQuery();

        }
        catch (Exception e)
        {

            throw e;
        }
        finally
        {
            // Close connection
            sqlCon.Close();
        }

错误发生在:

sqlCmd = new SqlCommand(sqlCmd.CommandText, sqlCon);

可能是什么问题??

【问题讨论】:

  • 这是因为您的sqlCmd 为空,并且您正尝试使用它来创建自己的实例。在该行中,您正在创建 SqlCommand 的新实例,并且在创建其对象之前访问其 CommandText。

标签: c# windows dll


【解决方案1】:

你在设置对应值之前调用SQL命令,你应该设置CommandText的值,然后实例化SQL命令

【讨论】:

  • 我解决了这个问题,但我想知道为什么我不能在 dll 文件中使用相同的代码,我需要在初始化阶段传递命令文本:sqlcmd = new sqlcommand(storedprocedure , sqlcon)
【解决方案2】:

您尚未创建sqlCmd 的实例,并且您试图将其CommandText 传递给创建该对象的进程。您似乎将存储过程作为参数传递给执行,因此请尝试以下操作:

sqlCmd = new SqlCommand(storedProcedure, sqlCon);

【讨论】:

    【解决方案3】:

    我肯定会尽量在最短的时间内保持您的连接畅通。我建议使用 using 语句。

    public void Try(string conStr, string storedProcedure) {
        using (var sqlCon = new SqlConnection(conStr)) {
            // create command, also a local variable
            var sqlCmd = new SqlCommand();
    
            // set connection
            sqlCmd.Connection = sqlCon
    
            //add command type
            sqlCmd.CommandType = CommandType.StoredProcedure;
    
            // add the stored procedure name
            sqlCmd.CommandText = storedProcedure;
    
            //Open connection
            sqlCon.Open();
    
            // Execute transaction
            sqlCmd.ExecuteNonQuery();
        }
    }
    

    【讨论】:

    • 好的@Maarten,试着回到你身边。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    相关资源
    最近更新 更多