通过C#代码从CSV文件插入访问表

时间:2013-10-06 11:56:48

标签: c# winforms ms-access odbc

我有这张桌子:

Items
====
Barcode (text)
Des (text)
Price (double)

我在d:\Items.csv上制作了csv文件,以便快速插入(12345,computer,120.44).....

我尝试像这样插入(C#WinForm程序):

Cmd = Conn.CreateCommand();
SQL = @"INSERT INTO Items SELECT * FROM [Text;DATABASE=" + @"d:" + @"\].[Items.txt];";
Cmd.CommandText = SQL;
Cmd.ExecuteNonQuery();

但我得到了2个错误:

1. Data type mismatch in criteria expression.

2. The field 'Items.Barcode ' cannot contain a Null value because the Required property for this field is set to True.  Enter a value in this field.

如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

以下C#代码适合我。它将C:\Users\Public\Items.csv导入到Access 2010数据库C:\Users\Public\Database1.accdb中名为[Items]的表中。 CSV文件的内容只是

12345,computer,120.44

代码是

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Odbc;

namespace myDbTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string myConnectionString;
            myConnectionString =
                    @"Driver={Microsoft Access Driver (*.mdb, *.accdb)};" +
                    @"Dbq=C:\Users\Public\Database1.accdb;";

            using (var con = new OdbcConnection())
            {
                con.ConnectionString = myConnectionString;
                con.Open();

                using (var cmd = new OdbcCommand())
                {
                    cmd.Connection = con;
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.CommandText =
                            @"INSERT INTO Items " +
                            @"SELECT * FROM [Text;FMT=Delimited;HDR=NO;IMEX=2;CharacterSet=437;ACCDB=YES;Database=C:\Users\Public].[Items#csv];";
                    cmd.ExecuteNonQuery();
                }
                con.Close();
            }
        }
    }
}