[技術] 使用SqlCommand.Parameters.Add (How to use SqlCommand.Parameters.Add)

[技術] 使用SqlCommand.Parameters.Add (How to use SqlCommand.Parameters.Add)

在此舉的範例為,將DataTable的資料放進資料庫裡。

   1: string connStr = "Data Source=localhost;UID=XXX;PWD=YYY;Database=DBName";
   2:  
   3: SqlConnection conn = new SqlConnection(connStr);
   4:  
   5: conn.Open();
   6:  
   7: // 讀取DataTable裡的每筆資料
   8: foreach (DataRow tRow in DataTable.Rows)
   9: {            
  10:     SqlCommand cmd = conn.CreateCommand();
  11:     
  12:     cmd.Parameters.Add("@ID", System.Data.SqlDbType.Decimal).Value = tRow["ID"];
  13:     
  14:     string sqlCom = "Insert into TableName(ID) values(@ID)";
  15:     
  16:     cmd.CommandText = sqlCom;
  17:     
  18:     cmd.ExecuteNonQuery();
  19:     
  20:     cmd.Dispose();
  21: }
  22: conn.Close();