尝试读取CSV文件,但值不会显示在SQL数据库中

时间:2017-01-04 16:00:54

标签: c# sql csv

我正在读取一个CSV文件,但它只使得SQL表有2列(IDtest)`但它不会用CSV文件中的值填充这些列。这是我得到的代码:

    public void GetDataTabletFromCSVFile2(string csv_file_path, string tablenaam)
    {
        string cn = ConfigurationManager.ConnectionStrings["Scratchpad"].ConnectionString;
        using (SqlConnection dbConnection = new SqlConnection(cn))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection = dbConnection;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = $@"CREATE TABLE  test (  
                [ID] INT IDENTITY (1, 1) NOT NULL, 
                [testingcolumn] VARCHAR (1023) NULL,
                CONSTRAINT [PK_{test}] PRIMARY KEY CLUSTERED ([ID] ASC) 
                )";
                try
                {
                    dbConnection.Open();
                    cmd.ExecuteNonQuery();
                }
                catch (SqlException e)
                {
                    MessageBox.Show(e.Message.ToString(), "Error Message");
                }
                finally
                {
                    dbConnection.Close();
                }
            }
        }


        string line;
        System.Data.DataTable csvData = new System.Data.DataTable();
        // Read the file and display it line by line.
        System.IO.StreamReader file = new System.IO.StreamReader(csv_file_path);
        while ((line = file.ReadLine()) != null)
        {
            DataRow newRow = csvData.NewRow();
            csvData.Rows.Add(newRow);
        }

        file.Close();
        InsertDataIntoSQLServerUsingSQLBulkCopy2(csvData, tablenaam);
    }


    static void InsertDataIntoSQLServerUsingSQLBulkCopy2(System.Data.DataTable csvFileData, string Tablename)
    {
        string cn = ConfigurationManager.ConnectionStrings["Scratchpad"].ConnectionString;
        using (SqlConnection dbConnection = new SqlConnection(cn))
        {
            dbConnection.Open();
            string sqlTrunc = "TRUNCATE TABLE " + Tablename;
            SqlCommand cmd = new SqlCommand(sqlTrunc, dbConnection);
            cmd.ExecuteNonQuery();
            using (SqlBulkCopy s = new SqlBulkCopy(dbConnection))
            {
                s.ColumnMappings.Clear();
                s.DestinationTableName = Tablename;
                foreach (var column in csvFileData.Columns)
                    s.ColumnMappings.Add(column.ToString(), column.ToString());
                s.WriteToServer(csvFileData);
                dbConnection.Close();
            }
        }
    }

我的SQL表现在看起来像这样:

------------
| ID | test|
------------
|null|null |
------------

虽然看起来应该是这样的:

-------------
| ID | test |
-------------
|1   |value1|
-------------
|2   |value2|
-------------
|3   |value3|
-------------
编辑:这也不起作用:

        string line;
        System.Data.DataTable csvData = new System.Data.DataTable();
        // Read the file and display it line by line.
        System.IO.StreamReader file = new System.IO.StreamReader(csv_file_path);
        int i = 0;

        DataColumn datecolumn = new DataColumn("ID");
        datecolumn.AllowDBNull = true;
        csvData.Columns.Add(datecolumn);

        DataColumn datecolumn2 = new DataColumn("RunTimeGroupCheck");
        datecolumn.AllowDBNull = true;
        csvData.Columns.Add(datecolumn2);

        while ((line = file.ReadLine()) != null)
        {
            var id = (i++); //Code this method
            var test = (line); //Code this method
            csvData.Rows.Add(id, test);
        }

        file.Close();
        InsertDataIntoSQLServerUsingSQLBulkCopy2(csvData, tablenaam);

3 个答案:

答案 0 :(得分:1)

在阅读CSV时,您没有对读取的数据做任何事情,因此您的DataTable实际上是空的:

 // Read the file and display it line by line.
        System.IO.StreamReader file = new System.IO.StreamReader(csv_file_path);
        while ((line = file.ReadLine()) != null)
        {
            DataRow newRow = csvData.NewRow();
            // HERE: YOU ARE MISSING PARSING line INTO newRow
            csvData.Rows.Add(newRow);
        }

答案 1 :(得分:1)

您忘记填充要添加的数据行,您正在正确地创建数据行DataRow newRow = csvData.NewRow();,但您必须填写您在线的信息。

while ((line = file.ReadLine()) != null)
{
    DataRow newRow = csvData.NewRow();
    //DataRow is empty
    csvData.Rows.Add(newRow);
}

试试这个

while ((line = file.ReadLine()) != null)
{
    var id = extractIdFromLine(line); //Code this method
    var test= extractTestFromLine(line); //Code this method
    csvData.Rows.Add(id, test);
}

选中此oficial post

答案 2 :(得分:1)

您需要正确的数据类型和正确插入。

public void GetDataTabletFromCSVFile2(string csv_file_path, string tablenaam)
{
    string cn = ConfigurationManager.ConnectionStrings["Scratchpad"].ConnectionString;
    using (SqlConnection dbConnection = new SqlConnection(cn))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.Connection = dbConnection;
            cmd.CommandType = CommandType.Text;
            // check if You really want test for table name, not tablenaam
            // mind that the column name is same as the DataTable's column name!!!!
            cmd.CommandText = $@"CREATE TABLE  test (
        [ID] INT IDENTITY (1, 1) NOT NULL, 
        [RunTimeGroupCheck] VARCHAR (1023) NULL, 
        CONSTRAINT [PK_Test] PRIMARY KEY CLUSTERED ([ID] ASC) 
        )";
            try
            {
                dbConnection.Open();
                cmd.ExecuteNonQuery();
            }
            catch (SqlException e)
            {
                MessageBox.Show(e.Message.ToString(), "Error Message");
            }
            finally
            {
                dbConnection.Close();
            }
        }
    }


    string line;
    System.Data.DataTable csvData = new System.Data.DataTable();
    DataColumn firstColumn = new DataColumn("ID", typeof(int));
    firstColumn.AutoIncrement = true; // This is the thing that enables You to leave the ID column. It will autoincrement.
    firstColumn.AutoIncrementSeed = 1;
    firstColumn.AutoIncrementStep = 1;
    csvData.Columns.Add(firstColumn);
    csvData.Columns.Add(new DataColumn("RunTimeGroupCheck", typeof(string)));
    // Read the file and display it line by line.
    System.IO.StreamReader file = new System.IO.StreamReader(csv_file_path);
    while ((line = file.ReadLine()) != null)
    {
        DataRow newRow = csvData.NewRow();
        // missing filling of data. You need the line to be put somewhere.
        // also mind, that the newRow["ID"] is not set to anything.
        newRow["RunTimeGroupCheck"] = line;
        csvData.Rows.Add(newRow);
    }

    file.Close();
    InsertDataIntoSQLServerUsingSQLBulkCopy2(csvData, tablenaam);
}


static void InsertDataIntoSQLServerUsingSQLBulkCopy2(System.Data.DataTable csvFileData, string Tablename)
{
    string cn = ConfigurationManager.ConnectionStrings["Scratchpad"].ConnectionString;
    using (SqlConnection dbConnection = new SqlConnection(cn))
    {
        dbConnection.Open();
        string sqlTrunc = "TRUNCATE TABLE " + Tablename;
        SqlCommand cmd = new SqlCommand(sqlTrunc, dbConnection);
        cmd.ExecuteNonQuery();
        using (SqlBulkCopy s = new SqlBulkCopy(dbConnection))
        {
            s.ColumnMappings.Clear();
            s.DestinationTableName = Tablename;
            foreach (var column in csvFileData.Columns)
                s.ColumnMappings.Add(column.ToString(), column.ToString());
            s.WriteToServer(csvFileData);
            dbConnection.Close();
        }
    }
}