2010-04-21 80 views

回答

0

你有DataTable

你會需要像:

// set up connection to your database 
using (SqlConnection con = new SqlConnection("your-connection-string-here")) 
{ 
    // define the INSERT statement - of course, I don't know what your table name 
    // is and which and how many fields you want to insert - adjust accordingly 
    string insertStmt = 
     "INSERT INTO dbo.YourTable(field1, field2, field3) " + 
     "VALUES(@field1, @field2, @field3)"; 

     // create SqlCommand object 
     using (SqlCommand cmd = new SqlCommand(insertStmt, con)) 
     { 
      // set up the parameters - again: I don't know your parameter names 
      // nor the parameters types - adjust to your needs 
      cmd.Parameters.Add("@field1", SqlDbType.Int); 
      cmd.Parameters.Add("@field2", SqlDbType.VarChar, 100); 
      cmd.Parameters.Add("@field3", SqlDbType.VarChar, 250); 

      // open connection 
      con.Open(); 

      // iterate over all the Rows in your data table 
      foreach (DataRow row in YourDataTable.Rows) 
      { 
      // assign the values to the parameters, based on your DataRow 
      cmd.Parameters["@field1"].Value = Convert.ToInt32(row["columnname1"]); 
      cmd.Parameters["@field2"].Value = row["columnname2"].ToString(); 
      cmd.Parameters["@field3"].Value = row["columnname3"].ToString(); 

      // call INSERT statement 
      cmd.ExecuteNonQuery(); 
      } 

      // close connection 
      con.Close(); 
     } 
    } 

當然,這有沒有錯誤檢查任何,你將需要添加一些的是自己(嘗試....漁獲物等) 。但基本上,如果我不能使用存儲過程,那就是我會這樣做的方式。

+0

感謝marc爲您的及時迴應 – Developer 2010-04-23 19:48:50

0

使用System.Data.SqlClient.SqlCommand

相關問題