我需要将两个具有不同列的csv文件导入到mysql数据库表中。
当我导入第二个文件时,表仍然使用第一个csv文件的数据,因此如果存在差异并添加不存在的数据,我需要一个方法或测试来更新数据。
我的代码看起来像这样:
方法Import_Bilan用于第一个文件,Import_data用于第二个文件。
private void Import_Bilan_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
string[] f = file.Split('\\');
// to get the only file name
string fn = f[(f.Length) - 1];
string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string dest = path + @"\upload\" + fn;
//to copy the file to the destination folder
File.Copy(file, dest, true);
MessageBox.Show("File Uploaded !!");
//to copy the file to the destination folder
File.Copy(file, dest, true);
MySqlConnection con = new MySqlConnection("datasource=localhost;database=***;port=3306;username=root;password=root;SslMode=none;AllowUserVariables=true");
var msbl = new MySqlBulkLoader(con)
{
TableName = "**",
FieldTerminator = ";",
FileName = dest,
NumberOfLinesToSkip = 1,
};
msbl.Columns.AddRange(new[] { "***", "***""@discard", "@discard","@discard", "@discard", "@discard"});
msbl.Load();
con.Close();
MessageBox.Show("Data bind to database !!");
}
}
private void Import_Data_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
string[] f = file.Split('\\');
// to get the only file name
string fn = f[(f.Length) - 1];
string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
string dest = path + @"\upload\" + fn;
//to copy the file to the destination folder
File.Copy(file, dest, true);
MessageBox.Show("File Uploaded !!");
//to copy the file to the destination folder
File.Copy(file, dest, true);
MySqlConnection con = new MySqlConnection("datasource=localhost;database=***;port=3306;username=root;password=root;SslMode=none;AllowUserVariables=true");
var msbl = new MySqlBulkLoader(con)
{
TableName = "****",
FieldTerminator = ";",
FileName = dest,
NumberOfLinesToSkip = 1,
};
msbl.Columns.AddRange(new[] { "@discard", "***" });
msbl.Load();
con.Close();
MessageBox.Show("Data bind to database !!");
}
}
根据传递给msbl.Columns.AddRange
的列名,您的两个输入CSV文件似乎具有非常不同的数据类型和列数。 (如果这不正确,请使用有关CSV文件结构的信息编辑您的问题。)
如果这是真的,我会建议两种不同的方法之一:
使用像CsvHelper这样的库来读取C#中的两个CSV文件并将数据连接在一起(例如,通过基于共享密钥创建Dictionary
),然后将行(一次一行)插入MySQL。这可能最终会变慢,并且可能需要更多代码。所以,你可以......
从上面的代码开始,但将CSV文件加载到两个临时表中;让我们称他们为exercices1
和exercices2
。 (它们可以与exercices
具有相同的架构,或者如果您愿意,可以为每个CSV创建自定义架构。)
然后执行MySQL INSERT INTO语句:
INSERT INTO exercices (all, the, output, columns, that, you, want)
SELECT e1.column1, e1.column2, e2.column1, e2.column2
FROM exercices e1 JOIN exercices e2
WHERE e1.some_column = e2.some_column;
显然,具体细节取决于CSV文件的确切结构,它们包含哪些数据,它们共有哪些列(您可以加入)等等。
完成此操作后,您可以删除加载CSV数据的两个表。