-1

私は自分のアプリケーションでこのメソッドを作成しましたが、正常に機能します。そのための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);

何が問題になるのでしょうか?

4

3 に答える 3

0

対応する値を設定する前に SQL コマンドを呼び出している場合は、CommandText の値を設定してから SQL コマンドをインスタンス化する必要があります。

于 2012-11-16T12:57:32.473 に答える
0

のインスタンスを作成しておらず、そのオブジェクトを作成するプロセスsqlCmdに渡そうとしています。CommandText実行するパラメータとしてストアド プロシージャを渡しているように見えるので、次のようにしてみてください。

sqlCmd = new SqlCommand(storedProcedure, sqlCon);
于 2012-11-16T12:59:21.127 に答える
0

私は間違いなくあなたの接続を可能な限り最短時間開いたままにしようとします. 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();
    }
}
于 2012-11-16T13:00:24.040 に答える