[技术] 使用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();