Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
需要优化c#代码以将CSV行插入MySql_C#_Mysql_Visual Studio_Sql Insert - Fatal编程技术网

需要优化c#代码以将CSV行插入MySql

需要优化c#代码以将CSV行插入MySql,c#,mysql,visual-studio,sql-insert,C#,Mysql,Visual Studio,Sql Insert,以下是我想要实现的目标。。。单击一个按钮,我想: 将live“users”表的现有数据复制到“old_users”表以进行备份 截断现有的“new_users”表以准备接受新行 解析CSV文件,将数据插入“new_users”表 截断现有的“users”表,然后将“new_users”表的数据复制到“users”表 我不是一个日常程序员,很久没有创建程序了。但我已经拼凑了一些代码来得到一些有用的东西。以下是我目前的代码: using System; using System.Collection

以下是我想要实现的目标。。。单击一个按钮,我想:

  • 将live“users”表的现有数据复制到“old_users”表以进行备份
  • 截断现有的“new_users”表以准备接受新行
  • 解析CSV文件,将数据插入“new_users”表
  • 截断现有的“users”表,然后将“new_users”表的数据复制到“users”表
  • 我不是一个日常程序员,很久没有创建程序了。但我已经拼凑了一些代码来得到一些有用的东西。以下是我目前的代码:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using Microsoft.VisualBasic.FileIO;
    using Renci.SshNet;
    using Renci.SshNet.Common;
    using MySql.Data.MySqlClient;
    
    namespace ValidationImport
    {
    public partial class ValiationImport : Form
    {
        public ValiationImport()
        {
            InitializeComponent();
        }
    
        private void Form1_Load(object sender, EventArgs e)
        {
    
        }
    
        private void btnImportToDatabase_Click(object sender, EventArgs e)
        {
            try
            {
                using (var client = new SshClient("1.1.1.1", "[username]", "[password]")) // establishing ssh connection to server where MySql is hosted
                {
                    client.Connect();
                    if (client.IsConnected)
                    {
                        var portForwarded = new ForwardedPortLocal("127.0.0.1", 3306, "127.0.0.1", 3306);
                        client.AddForwardedPort(portForwarded);
                        portForwarded.Start();
                        using (MySqlConnection con = new MySqlConnection("SERVER=localhost;PORT=3306;UID=[username];PASSWORD=[password];DATABASE=[dbname]")) // MySql database credentials
                        {
                            con.Open();
    
                            // Copying over the users table (with structure and indexes) to the old_users table. Truncating the new_users table to prepare for new data.
                            using (MySqlCommand cmd = new MySqlCommand("DROP TABLE test_old_users; CREATE TABLE test_old_users LIKE test_users; INSERT test_old_users SELECT * FROM test_users; TRUNCATE TABLE test_new_users;", con))
                            {
                                cmd.Connection = con;
                                cmd.CommandType = CommandType.Text;
                                cmd.ExecuteNonQuery();
                            }
    
                            string fileName = "";
                            // Select the Validation file to import
                            OpenFileDialog dlg = new OpenFileDialog();
                            if (dlg.ShowDialog() == DialogResult.OK)
                                fileName = dlg.FileName;
    
                            if (fileName != "")
                            {
                                using (TextFieldParser parser = new TextFieldParser(fileName))
                                {
                                    parser.TextFieldType = FieldType.Delimited;
                                    parser.SetDelimiters("|");
                                    parser.ReadLine(); // Skip the first row of field title headers
                                    while (!parser.EndOfData)
                                    {
                                        //Copy each row individually over to the MySql table
                                        string[] row = parser.ReadFields();
    
                                        using (MySqlCommand cmd = new MySqlCommand("INSERT INTO test_new_users (`Indv Id`, `Last Name`, `First Name`, `Middle Name`, `Birth date`, `Indv Addr Line 1`, `Indv Addr Line 2`, `Indv Addr Line 3`, `Indv City`, `Indv State`, `Indv Zip`, `Indv Country`, `Local Id`, `Local Name`, `Local User Id`, `Uniserv Id`, `Uniserv Name`, `Uniserv User Id`, `Chapter Name`, `Chapter User Id`, `Employer Id`, `Employer Name`, `Work Location Id`, `Work Location Name`, `Work Location User Id`, `Group Id`, `Group Name`, `Group Type Id`, `Group Type Name`, `SEA P01`, `Home  Phone`, `Home Phone principal Ind`, `Home Phone Unlisted Ind`, `Mobile Phone`, `Mobile Phone Principal Ind`, `Mobile Phone Unlisted Ind`, `Home Email`, `Home Email Principal Ind`, `Work Email`, `Work Email Principal Ind`, `Other Email`, `Other Email Principal Ind`) VALUES (@IndvId, @LastName, @FirstName, @MiddleName, @BirthDate, @IndvAddrLine1, @IndvAddrLine2, @IndvAddrLine3, @IndvCity, @IndvState, @IndvZip, @IndvCountry, @LocalId, @LocalName, @LocalUserId, @UniservId, @UniservName, @UniservUserId, @ChapterName, @ChapterUserId, @EmployerId, @EmployerName, @WorkLocationId, @WorkLocationName, @WorkLocationUserId, @GroupId, @GroupName, @GroupTypeId, @GroupTypeName, @SEAP01, @HomePhone, @HomePhonePrincipalInd, @HomePhoneUnlistedInd, @MobilePhone, @MobilePhonePrincipalInd, @MobilePhoneUnlistedInd, @HomeEmail, @HomeEmailPrincipalInd, @WorkEmail, @WorkEmailPrincipalInd, @OtherEmail, @OtherEmailPrincipalInd);", con))
                                        {
                                            cmd.CommandType = CommandType.Text;
                                            cmd.Parameters.AddWithValue("@IndvId", row[0]);
                                            cmd.Parameters.AddWithValue("@LastName", row[1]);
                                            cmd.Parameters.AddWithValue("@FirstName", row[2]);
                                            cmd.Parameters.AddWithValue("@MiddleName", row[3]);
                                            cmd.Parameters.AddWithValue("@BirthDate", row[4]);
                                            cmd.Parameters.AddWithValue("@IndvAddrLine1", row[5]);
                                            cmd.Parameters.AddWithValue("@IndvAddrLine2", row[6]);
                                            cmd.Parameters.AddWithValue("@IndvAddrLine3", row[7]);
                                            cmd.Parameters.AddWithValue("@IndvCity", row[8]);
                                            cmd.Parameters.AddWithValue("@IndvState", row[9]);
                                            cmd.Parameters.AddWithValue("@IndvZip", row[10]);
                                            cmd.Parameters.AddWithValue("@IndvCountry", row[11]);
                                            cmd.Parameters.AddWithValue("@LocalId", row[12]);
                                            cmd.Parameters.AddWithValue("@LocalName", row[13]);
                                            cmd.Parameters.AddWithValue("@LocalUserId", row[14]);
                                            cmd.Parameters.AddWithValue("@UniservId", row[15]);
                                            cmd.Parameters.AddWithValue("@UniservName", row[16]);
                                            cmd.Parameters.AddWithValue("@UniservUserId", row[17]);
                                            cmd.Parameters.AddWithValue("@ChapterName", row[18]);
                                            cmd.Parameters.AddWithValue("@ChapterUserId", row[19]);
                                            cmd.Parameters.AddWithValue("@EmployerId", row[20]);
                                            cmd.Parameters.AddWithValue("@EmployerName", row[21]);
                                            cmd.Parameters.AddWithValue("@WorkLocationId", row[22]);
                                            cmd.Parameters.AddWithValue("@WorkLocationName", row[23]);
                                            cmd.Parameters.AddWithValue("@WorkLocationUserId", row[24]);
                                            cmd.Parameters.AddWithValue("@GroupId", row[25]);
                                            cmd.Parameters.AddWithValue("@GroupName", row[26]);
                                            cmd.Parameters.AddWithValue("@GroupTypeId", row[27]);
                                            cmd.Parameters.AddWithValue("@GroupTypeName", row[28]);
                                            cmd.Parameters.AddWithValue("@SEAP01", row[29]);
                                            cmd.Parameters.AddWithValue("@HomePhone", row[30]);
                                            cmd.Parameters.AddWithValue("@HomePhonePrincipalInd", row[31]);
                                            cmd.Parameters.AddWithValue("@HomePhoneUnlistedInd", row[32]);
                                            cmd.Parameters.AddWithValue("@MobilePhone", row[33]);
                                            cmd.Parameters.AddWithValue("@MobilePhonePrincipalInd", row[34]);
                                            cmd.Parameters.AddWithValue("@MobilePhoneUnlistedInd", row[35]);
                                            cmd.Parameters.AddWithValue("@HomeEmail", row[36]);
                                            cmd.Parameters.AddWithValue("@HomeEmailPrincipalInd", row[37]);
                                            cmd.Parameters.AddWithValue("@WorkEmail", row[38]);
                                            cmd.Parameters.AddWithValue("@WorkEmailPrincipalInd", row[39]);
                                            cmd.Parameters.AddWithValue("@OtherEmail", row[40]);
                                            cmd.Parameters.AddWithValue("@OtherEmailPrincipalInd", row[41]);
                                            cmd.ExecuteNonQuery();
                                        }
                                    }
                                }
                            }
    
                            // Copying over the new_users table (with structure and indexes) to the users table.
                            using (MySqlCommand cmd = new MySqlCommand("DROP TABLE test_users; CREATE TABLE test_users LIKE test_new_users; INSERT test_users SELECT * FROM test_new_users;", con))
                            {
                                cmd.Connection = con;
                                cmd.CommandType = CommandType.Text;
                                cmd.ExecuteNonQuery();
                            }
                            con.Close();
                        }
                        client.Disconnect();
                    }
                    else
                    {
                        Console.WriteLine("Client cannot be reached...");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
    }
    
    一切都在“工作”。。。除非我在VisualStudio中处于调试模式时出错。一些关于处理时间太长的问题。哦,正如你所知,CSV文件中大约有38000行需要插入到表中


    如果您有任何建议或新代码供我试用,我将不胜感激!谢谢大家!

    在许多情况下,如果您最终在数据上循环,对不同的数据重复运行相同的查询,您可以通过在循环开始之前准备一次查询来帮助加快速度

    using (var cn = new MySqlConnection(...))
    using (var cmd = cn.CreateCommand())
    {
       // Setup command
       cmd.CommandText = "Some query";
       var param1 = cmd.Parameters.Add("@paramName1", MySQLDbType.sometype);
       var param2 = cmd.Parameters.Add("@paramName2", MySQLDbType.sometype);
       cmd.Prepare();
    
       // get data
    
       // loop over data
       foreach(var d in data)
       {
          param1.Value = d.somevalue;
          param2.Value = d.anothervalue;
          cmd.ExecuteNonQuery();
       }
    }
    
    您还可以通过索引对参数进行寻址,如
    cmd.parameters[0].Value

    以这种方式准备语句可以减少每次迭代时解析查询本身的工作开销


    在我必须处理的一种情况下,我发现最好的解决方案是将上述内容与使用多个值列表的插入查询相结合,其形式为
    插入X(a,b,c)值(?,,,,,(,,,,,?),(,,,,,,?)
    。它使实际实现变得更加复杂(必须适当地处理最后的“剩余部分”,这些“剩余部分”无法填满所有的值列表),并依赖于按索引处理参数;但确实起了作用


    编辑:处理ssh连接关闭的伪代码

    connect = true
    Open datasource
    while (data remains)
    {
       if (connect)
       {
          init ssh client
          init mysql connection
          init mysql command
          connect = false
       }
       while (data remains and enough time remaining)
       {
          get next data
          set command parameters
          execute command
       }
       if (not enough time remaining)
       {
           close current connection and client
           connect = true
       }
    }
    

    对于导入部分,您应该能够创建用于插入的命令对象一次,添加它的参数一次,并在循环之前准备它;然后,只需设置参数值并为每个迭代执行。至于第一个“备份”部分;你确定它起作用了吗?上次我使用MySqlCommands时,它们的默认模式不允许在一次执行中执行多个查询。如果解析部分的速度较慢,可以使用ExcelDataReader解析文件,而且速度很快。如果是你的问题,我可以分享一个示例代码。速度慢是在插入部分。它通过了大约2000行,然后出现了关于它的错误,这需要很长时间。我一次只解析一行,并将该行插入MySql表。我愿意听取关于如何做得更好的建议。Uueerdo,你能更详细地谈谈你评论的前半部分吗?是的,我确信备份部分在一个execute命令中使用多个查询时工作正常。我应该解析CSV文件并将其转储到datatable或其他什么东西中?基本上是的。在您的问题的上下文中,这可能是parser init,您可以用while替换foreach,并用
    ReadFields
    调用开始每个迭代。然后执行类似于
    param1.Value=row[0]的操作。我作为示例使用的收集循环逻辑没有什么特别之处,只是为了简洁起见。导入部件正在设置命令,定义其参数,并在循环之前准备该命令。。。然后在循环中分配(而不是添加)参数值。我完成了上面建议的所有操作,但仍然得到相同的错误。下面是我得到的确切错误:ContextSwitchDeadlock发生消息:托管调试助手“ContextSwitchDeadlock”显然在[exe文件位置]中检测到问题,正在调用
    Application.DoEvents()修复了该问题。解析38000行并将其插入远程MySql表大约需要15分钟,但无论如何。。。很有效,哈哈。谢谢你的帮助!啊。。。我认为ssh隧道在大约10分钟时超时。它通过了大约1/2的文件。我想我必须先解析数据并将其保存到datatable中。然后可能会创建一个巨大的insert语句,这样ssh隧道只打开几秒钟?