4

Windows アプリケーションには、同じ構造を使用してクエリを実行する多数のコード ブロックがあります。私のコードにいくつかの新しいものを追加した後、これらはエラーのために機能しなくなりました:

「ExecuteNonQuery: 接続プロパティが初期化されていません」

コードのブロックはすべて次のようになります。

sc.Open();
cmd = new SqlCommand("UPDATE bin SET serialNumber=" + tb_computername.Text + " WHERE binNumber=" + binNumber);
cmd.ExecuteNonQuery();
sc.Close();
break;

新しいコードはこれを行います:

//Find Open BIN
int binNumber = 0;
int binIndex = 0;
string queryString = "SELECT * FROM bin";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, scb);
DataSet binNumbers = new DataSet();
adapter.Fill(binNumbers, "bin");
for (int i = 0; i < 150; i++)
{
    binNumber++;                    
    if(binNumbers.Tables["bin"].Rows[binIndex]["serialNumber"].ToString() == "")
{
sc.Open();
cmd = new SqlCommand("UPDATE bin SET serialNumber=" + tb_computername.Text + " WHERE binNumber=" + binNumber);
cmd.ExecuteNonQuery();
sc.Close();
break;
}
binIndex++;

これらの接続は、クラスの上部で定義されています。

4

2 に答える 2

3

オブジェクトに割り当てる必要がありSqlConnectionます。

 cmd.Connection = connection;

connection接続文字列などを持つSqlConnectionオブジェクトはどこにありますか。

また、良い習慣として、次のようにラップする必要がありますusing

 using (SqlConnection connection = new SqlConnection("ConnectionString")) { 
     cmd.Connection = connection;
 } 

また、SQL インジェクション攻撃を防ぐためのパラメーター化されたクエリ。

于 2013-09-13T13:45:30.890 に答える
0

実行する前に、sqlconnection オブジェクトを sqlcommand オブジェクトに渡す必要があります。

Sqlcommand には次のコンストラクターがあります。

  1. Sqlコマンド()
  2. SqlCommand(文字列)
  3. SqlCommand(文字列、SqlConnection)
  4. SqlCommand(文字列、SqlConnection、SqlTransaction)
  5. SqlCommand(文字列、SqlConnection、SqlTransaction、SqlCommandColumnEncryptionSetting)

1. デフォルト コンストラクターまたは 2. 1 つのパラメーター (クエリ) を持つパラメーター化されたコンストラクターを使用している場合、次のように接続を設定する必要があります。

   SqlCommand.Connection = SqlConnection;

以下は、実際のコード スニペットです。

   //create a connection object
  using (SqlConnection connection = new SqlConnection(connectionString))
    {
     //create command object, and pass your string query & connection object.
     //we can call the default constructor also and later assign these values
       SqlCommand command = new SqlCommand(queryString, connection);   
    //open the connection here,
      command.Connection.Open();
    //execute the command.
      command.ExecuteNonQuery();
    }

接続が常に閉じていることを確認するには、using ブロック内で接続を開いて、コードがブロックを終了したときに接続が自動的に閉じられるようにする必要があります。

于 2020-05-14T09:56:03.330 に答える