System.ArgumentException:“列不属于 table。” - 如何修复此错误(将数据从 csv 文件导入到 mysql 数据库)?

System.ArgumentException: „Column does not belong to table .” - how to fix this error (import data from csv file to mysql database)?

在这种情况下,我想将数据从 csv 文件导入到 mysql 数据库。现在我已经编写了插入该文件的方法:

1) Select 扩展名为“*.csv”的文件

2) 在 select 之后,它通过分隔逗号加载数据,如果是空单元格则继续。

        private DataTable ImportFile()
        {
            DataTable imported_data = new DataTable();

            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "Open csv file";
            ofd.DefaultExt = "*.csv";
            ofd.Filter = "Documents (*.csv)|*.csv";
            ofd.ShowDialog();

            FileInfo fi = new FileInfo(ofd.FileName);
            string FileName1 = ofd.FileName;
            string excel = fi.FullName;

            using(StreamReader sr = new StreamReader(excel))
            {
                string header = sr.ReadLine();
                if (string.IsNullOrEmpty(header))
                {
                    MessageBox.Show("Not found or loaded not correct file.");
                    return null;
                }

                string[] header_columns = header.Split(',');
                foreach(string header_column in header_columns)
                {
                    imported_data.Columns.Add(header_column);
                }

                while (!sr.EndOfStream)
                {
                    string line = sr.ReadLine();

                    if (string.IsNullOrEmpty(linia)) continue;

                    string[] fields = line.Split(',');
                    DataRow imported_row = imported_data.NewRow();

                    for (int i = 0; i < fields.Count(); i++)
                    {
                        imported_row[i] = fields[i];
                    }

                    imported_data.Rows.Add(imported_row);
                }
            }
            return imported_data;
        }

然后第二种方法是当它与 mysql 数据库连接时它向该数据库插入值:

private void save_modules(DataTable imported_data)
{
    string connection = "datasource=localhost;port=3306;username=root;password=";
    using (MySqlConnection conn = new MySqlConnection(connection))
    {
        conn.Open();
        foreach (DataRow importRow in imported_data.Rows)
        {
            string query3 = @"INSERT IGNORE INTO try1.modules (NAME, ID_PROJECT) SELECT @NAME, projekty.ID 
                FROM try1.projects WHERE projects.PROJECT_NAME = @PROJECT_NAME;";

            MySqlCommand cmd = new MySqlCommand(query3, conn);

            cmd.Parameters.AddWithValue("@NAME", importRow["NAME"]);
            cmd.Parameters.AddWithValue("@PROJECT_NAME", importRow["PROJECT_NAME"]);

            cmd.ExecuteNonQuery();
        }
        conn.Close();
    }  
    MessageBox.Show("Imported to database");
}

点击 btn_import_projects 时的事件。

    private void btn_import_projects_Click(object sender, EventArgs e)
    {
            DataTable imported_data = ImportFile();
            save_modules(imported_data);
            frm2.loaddataalldatagridview();      
    }

当我从 3 个代码行编译连接到 1 个代码时出现异常错误:

System.ArgumentException: „Column NAME does not belong to table .”

并在代码行显示:

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

我有一个问题,如何解决这个错误?我应该将代码行形式 cmd.Parameters.AddWithValue 更改为 cmd.Parameters.Add 吗?有任何想法吗?提前致谢。

更新

对于只有 1 列的情况,代码:

private void save_projects(DataTable imported_data)
{
    string connection = "datasource=localhost;port=3306;username=root;password=";
    using (MySqlConnection conn = new MySqlConnection(connection))
    {
        conn.Open();
        foreach (DataRow importRow in imported_data.Rows)
        {
                string query2 = "INSERT IGNORE INTO try1.projects(PROJECT_NAME) VALUES (@PROJECT_NAME);";

                MySqlCommand cmd = new MySqlCommand(query2, conn);

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

            cmd.ExecuteNonQuery();
        }
        conn.Close();
    }  
    MessageBox.Show("Imported to database");
}

运行正常,没有任何小错误。

有我的代码:

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 System.Collections;
using System.Data.OleDb;
using System.IO;
using System.Configuration;
using MySql.Data.MySqlClient;

namespace ControlDataBase
{
    public partial class Import_data_mysql : Form
    {
        public Import_data_mysql()
        {
            InitializeComponent();
        }
        New_Tables frm2 = (New_Tables)Application.OpenForms["New_Tables"];

        private DataTable ImportFile()
        {
            DataTable imported_data = new DataTable();

            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Title = "Open csv file";
            ofd.DefaultExt = "*.csv";
            ofd.Filter = "Documents (*.csv)|*.csv";
            ofd.ShowDialog();

            FileInfo fi = new FileInfo(ofd.FileName);
            string FileName1 = ofd.FileName;
            string excel = fi.FullName;

            using(StreamReader sr = new StreamReader(excel))
            {
                string header = sr.ReadLine();
                if (string.IsNullOrEmpty(header))
                {
                    MessageBox.Show("Not found or loaded not correct file.");
                    return null;
                }

                string[] header_columns = header.Split(',');
                foreach(string header_column in header_columns)
                {
                    imported_data.Columns.Add(header_column);
                }

                while (!sr.EndOfStream)
                {
                    string line = sr.ReadLine();

                    if (string.IsNullOrEmpty(line)) continue;

                    string[] fields = line.Split(',');
                    DataRow imported_row = imported_data.NewRow();

                    for (int i = 0; i < fields.Count(); i++)
                    {
                        imported_row[i] = fields[i];
                    }

                    imported_data.Rows.Add(imported_row);
                }
            }
            return imported_data;
        }

        private void save_modules(DataTable imported_data)
        {
            string connection = "datasource=localhost;port=3306;username=root;password=";
            using (MySqlConnection conn = new MySqlConnection(connection))
            {
                conn.Open();
                foreach (DataRow importRow in imported_data.Rows)
                {
                    string query3 = @"INSERT IGNORE INTO try1.modules (NAME, ID_PROJECT) SELECT @NAME, projekty.ID 
                        FROM try1.projects WHERE projects.PROJECT_NAME = @PROJECT_NAME;";

                    MySqlCommand cmd = new MySqlCommand(query3, conn);

                    cmd.Parameters.AddWithValue("@NAME", importRow["NAME"]);
                    cmd.Parameters.AddWithValue("@PROJECT_NAME", importRow["PROJECT_NAME"]);

                    cmd.ExecuteNonQuery();
                }
                conn.Close();
            }  
            MessageBox.Show("Imported to database");
        }

        private void btn_import_projects_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable imported_data = ImportFile();
                save_modules(imported_data);
                frm2.loaddataalldatagridview();
            }

            catch
            {
                MessageBox.Show("Select invalid file to import data.");
            }            
        }
    }
}

好的。响应@soohoonigan 的建议,我只需要更改两行代码:

string[] header_columns = header.Split(',');
string[] fields = line.Split(',');

发现.csb文件中是用这些“;”隔开的标志,所以我将这些行更改为:

string[] header_columns = header.Split(';');
string[] fields = line.Split(';');

并且工作正常。非常感谢队友。 :)