2015-02-11 81 views
-4

对于我的培训生,我必须做一些SQL请求。如何在一次执行多个请求

我尝试这transfert从csv文件数据到SQL服务器数据库

string str = Path.GetFullPath("."); 
    String conn = @"Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=""Text;HDR=No;FMT=Delimited"";Data Source="+str+""; 
    string strCnx = "Database=" + ConfigurationManager.AppSettings["base"] + ";data source=" + ConfigurationManager.AppSettings["servername"] + ";User Id=" + ConfigurationManager.AppSettings["user"] + ";Password=" + ConfigurationManager.AppSettings["password"] + ";Connect Timeout=10"; 
    // Open a sourceConnection to the AdventureWorks database. 
    //using (OleDbConnection sourceConnection = new OleDbConnection(strCnx)) 
    { 
     //sourceConnection.Open(); 

     // Get data from the source table as a SqlDataReader. 
     OleDbConnection cn = new OleDbConnection(conn); 
     OleDbCommand commandSourceData = new OleDbCommand("SELECT * FROM [" + ConfigurationManager.AppSettings["csvname"] + "]", cn); 
     OleDbDataAdapter da = new OleDbDataAdapter(commandSourceData); 
     cn.Open(); 
     OleDbDataReader reader = commandSourceData.ExecuteReader(); 

     // Open the destination connection. In the real world you would 
     // not use SqlBulkCopy to move data from one table to the other 
     // in the same database. This is for demonstration purposes only. 
     using (SqlConnection destinationConnection = new SqlConnection(strCnx)) 
     { 
      destinationConnection.Open(); 

      // Set up the bulk copy object. 
      // Note that the column positions in the source 
      // data reader match the column positions in 
      // the destination table so there is no need to 
      // map columns. 
      using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection)) 
      { 
       bulkCopy.DestinationTableName = "GudsisUser"; 

       bulkCopy.WriteToServer(reader); 
      } 
      Console.WriteLine("Press Enter to finish."); 
      Console.ReadLine(); 
     } 

但应用程序返回一个错误消息:无法解析字符串值转换为NCHAR值

我不知道如果我PROGRAMM正确与否

+0

你说什么样的“请求”,你是否试图逐一插入记录? – Habib 2015-02-11 15:40:57

+0

您可以对DataSet进行所有数据修改,并隐藏更新或插入的实际过程,但最终它将始终是针对您的数据库执行的INSERT或UPDATE语句。 – Filburt 2015-02-11 15:43:00

+0

发布一些代码。你的问题真的很模糊,很难理解,没有任何代码 – Paolo 2015-02-11 15:43:34

回答

1

我猜你在找什么东西叫BULK INSERT(做一个DB请求中的一切吗?)

如果是这样,看看答案here

+0

此外,这里有一个非常好的通用解决方案:http://blog.developers.ba/bulk-insert-generic-list-sql-server-minimum-lines-code/ – quetzy 2015-02-11 15:55:05

+0

我需要“存储”我的请求和他的参数来执行循环中的所有请求。 – 2015-02-11 16:02:27

+0

对于您想要执行的操作,无法在循环中每次创建和执行SqlCommand。在循环前面创建SqlCommand,只将值加载到循环内的表中,并在循环后仅执行一次批量插入(包含所有数据)。 对于实现的想法,请检查两个链接。 – quetzy 2015-02-11 16:11:40