试图将csv文件解析为访问数据库c#

时间:2017-11-23 23:11:18

标签: c# csv ms-access

我一直在使用此功能来获取用户选择的csv文件并将其解析为访问数据库。经过多次试验和错误并在此处阅读后,该东西将编译并运行而不会崩溃,但没有值插入到表中。这是我目前所在的地方。

private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
    productFileName = productOpenDialog.SafeFileName;
    productFilePath = Path.GetDirectoryName(productOpenDialog.FileName);
    string connectionString = String.Format("Provider = Microsoft.ACE.OLEDB.12.0; Data Source ={0}"+"\\VendorDB.accdb;Persist Security Info = False;", Environment.CurrentDirectory);

    string selectSQL = String.Format(@"SELECT * FROM [" + productFileName + "]"); 


    using (OleDbConnection connection = new OleDbConnection(String.Format(@"Provider = Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Text;", productFilePath)))
    {
        using (OleDbCommand command = new OleDbCommand(selectSQL, connection))
        {

            using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
            {
                DataTable dataTable = new DataTable();
                adapter.Fill(dataTable);

                //create connection to Access DB
                OleDbConnection DBconn = new OleDbConnection(connectionString);
                OleDbCommand cmd = new OleDbCommand();
                //set cmd settings
                cmd.Connection = DBconn;
                //cmd.CommandType = CommandType.Text;
                //open DB connection
                DBconn.Open();

                //read each row in the Datatable and insert that record into the DB
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    cmd.CommandText = "INSERT INTO Product_List (ProductID, ProductName, Description, InventoryItem, Price, CaseSize, SalespersonID)" +
                                     " VALUES ('" + dataTable.Rows[i].ItemArray.GetValue(0) + "','" + dataTable.Rows[i].ItemArray.GetValue(1) + "','" + dataTable.Rows[i].ItemArray.GetValue(2) +
                                         "','" + dataTable.Rows[i].ItemArray.GetValue(3) + "','" + dataTable.Rows[i].ItemArray.GetValue(4) + "','" + dataTable.Rows[i].ItemArray.GetValue(5) +
                                         "','" + dataTable.Rows[i].ItemArray.GetValue(6) + "')";

                    cmd.ExecuteNonQuery();

                }
                //close DB.connection
                DBconn.Close();

            }
        }
    }
}

我知道字段中的数据类型可能存在问题,因此我删除了DateTime并将价格更改为短数字,因此所有数据都是字符串和数字。尽管从csv文件成功加载了DataTable,但没有任何值插入到访问中。

0 个答案:

没有答案