【问题标题】:How to carry out multiple requests at once如何一次执行多个请求
【发布时间】:2015-02-11 15:39:04
【问题描述】:

我正在尝试将数据从 .csv 文件传输到 sql-server 数据库。

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 值

【问题讨论】:

  • 你说的是什么“请求”,你是不是要一个一个地插入记录?
  • 您可以在 DataSet 上进行所有数据修改并隐藏更新或插入的实际过程,但最终它将始终是针对您的数据库执行的 INSERT 或 UPDATE 语句。
  • 发布一些代码。没有任何代码,你的问题真的很模糊,很难理解
  • 我不是 100% 确定你在问什么,但我认为你想一次性执行一批插入。在这种情况下,SqlDataAdapter.InsertCommand 可能会有所帮助。
  • 是的,你可以这样做。您可以填充数据表,而不是在查询后执行查询。然后创建一个在 sql 中接收表值参数的插入过程。然后,您只需传递您的 DataTable,它就会立即完成所有插入操作。另一种选择是使用 BULK INSERT,如下所示。

标签: c# sql-server loops request


【解决方案1】:

我猜你正在寻找一种叫做 BULK INSERT 的东西(在一个数据库请求中做所有事情?)

如果有,请查看答案here

【讨论】:

  • 此外,这里有一个非常好的通用解决方案:blog.developers.ba/…
  • 我需要“存储”我的请求和他的参数来执行循环中的所有请求
  • 对于您想要做的事情,您不能在循环中每次都创建和执行 SqlCommand。将 SqlCommand 的创建拉到循环前面,仅将值加载到循环内的表中,并在循环后仅执行一次批量插入(包含所有数据)。有关实施思路,请查看两个链接。
猜你喜欢
  • 1970-01-01
  • 2020-05-02
  • 2018-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-21
  • 2022-10-07
相关资源
最近更新 更多