簡體   English   中英

對象引用未設置為 dll 中對象的實例

[英]object reference not set to an instance of an object in dll

我在我的應用程序中編寫了這個方法,它工作正常。 我決定為它創建一個 DLL 文件。 但是同樣的方法給了我錯誤對象引用未設置為 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);

可能是什么問題?

您在設置其對應值之前調用 SQL 命令,您應該設置 CommandText 的值,然后實例化 SQL 命令

您尚未創建sqlCmd的實例,並且您試圖將其CommandText傳遞給創建該對象的進程。 您似乎將存儲過程作為要執行的參數傳遞,因此請嘗試以下操作:

sqlCmd = new SqlCommand(storedProcedure, sqlCon);

我肯定會盡量在最短的時間內保持您的連接暢通。 我建議使用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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM