私は私のアプリケーションでこのメソッドを書いて、それは正常に動作します。私はそれのための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);
何が問題なの?
回答:
回答№1は0SQLコマンドを呼び出してその値を設定する前に、CommandTextの値を設定してSQLコマンドをインスタンス化する必要があります
回答№2の場合は0
あなたは、 sqlCmd
あなたはその CommandText
そのオブジェクトを作成するプロセスに渡します。実行するパラメータとしてストアドプロシージャを渡しているようですので、次のように試してみてください:
sqlCmd = new SqlCommand(storedProcedure, sqlCon);
回答№3の場合は0
私は間違いなくあなたの接続を可能な限り短時間で開こうとします。私は、 を使用して ステートメント。
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();
}
}