【解決方法】csvデータをSQLサーバーにインポートするためにcsvbulkcopyを適用する方法


csvbulkcopy を適用して、ウィンドウ アプリケーション フォームを使用して csv データを SQL Server にインポートする方法。

私が試したこと:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;using System.Windows.Forms;

private void btnbrowse_Click(object sender, EventArgs e)
{
	OpenFileDialog ofd = new OpenFileDialog();
	ofd.DefaultExt = ".csv";
	ofd.Filter = "Comma Separated (*.csv)|*.csv";
	ofd.ShowDialog();
	txtfilename.Text = ofd.FileName;
}

private DataTable GetDataFromFile()
{
	DataTable dt = new DataTable();

	try
	{
		using (StreamReader sr = new StreamReader(txtfilename.Text))
		{
			string header = sr.ReadLine();
			if (string.IsNullOrEmpty(header))
			{
				MessageBox.Show("no file data");
				return null;
			}
			string[] headerColumns = header.Split(',');
			foreach (string headerColumn in headerColumns)
			{
				dt.Columns.Add(headerColumn);
			}
			while (!sr.EndOfStream)
			{
				string line = sr.ReadLine();
				if (string.IsNullOrEmpty(line)) continue;
				string[] fields = line.Split(',');
				DataRow importedRow = dt.NewRow();

				for (int i = 0; i < fields.Count(); i++)
				{                                                  
					importedRow[i] = fields[i];
				}
				dt.Rows.Add(importedRow);  
			}
		}     
	}
	catch (Exception e)
	{
		Console.WriteLine("the file could not be read:");
		Console.WriteLine(e.Message);
	}
	return dt;
}

private void SaveImportDataToDatabase(DataTable test)
{ 
	using (SqlConnection conn = new SqlConnection(@"Data Source=Biiuty;
        Initial Catalog=Hbi; User Id=ida; Password=***"))
	{
		conn.Open();
		foreach (DataRow importRow in test.Rows)
		{                                                  
			SqlCommand cmd = new SqlCommand
			("INSERT INTO test (DateTime,Milliseconds,MachineAutoStartStop,Pressure,Batch,)" +
			 "VALUES (@DateTime,@Milliseconds,@MachineAutoStartStop,@Pressure,@Batch)", conn);

			DateTime rowDate;
			if (DateTime.TryParse((string)importRow["DateTime"], out rowDate))
			{
			   cmd.Parameters.AddWithValue("@DateTime", rowDate); 
			}
			else
			{
			   cmd.Parameters.AddWithValue("@DateTime", DBNull.Value);
			}

			cmd.Parameters.AddWithValue("@mili", importRow["mili"]);
			cmd.Parameters.AddWithValue("@Machine", importRow["Machine"]);
			

			cmd.ExecuteNonQuery();
		}
	}
}

解決策 1

私は簡単なGOOGLE検索を行いました: Csv データを SQL サーバー C# にインポートするために csvbulkcopy を適用する方法 – Google 検索[^]

そして、ここにいくつかの結果が返されます:
* ASP.Net で SqlBulkCopy を使用して CSV ファイル データをデータベースに一括インポートする[^]

* C#でCSVファイルをSQL Serverに一括挿入[^]

* CSV ファイルを SQL Server にインポートする方法[^]

これらが適切でない場合は、その検索で調べる必要がある他の多くの回答があります。

コメント

タイトルとURLをコピーしました