【问题标题】:Trying to read a CSV file, but values wont show in SQL database尝试读取 CSV 文件,但值不会显示在 SQL 数据库中
【发布时间】:2017-01-04 16:00:53
【问题描述】:

我正在读取一个 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);

【问题讨论】:

    标签: c# sql csv


    【解决方案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();
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      读取 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);
              }
      

      【讨论】:

        【解决方案3】:

        您忘记填充要添加的数据行,您正在正确地创建数据行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

        【讨论】:

        • 当我尝试这个时:` int i = 1; while ((line = file.ReadLine()) != null) { var id = (i++); //编码这个方法 var test = (line); //编码这个方法 csvData.Rows.Add(id, test); }` 它给了我一个错误:An unhandled exception of type 'System.ArgumentException' occurred in System.Data.dll Additional information: Input array is longer than the number of columns in this table.
        • 是的,可能是我误解了你的表格,我以为你有两列,但似乎只有一列。但是,如果您看到该帖子,我建议您将有更好的方法来做到这一点。
        • @wouterdejong 如果您使用标识列 [ID] INT IDENTITY (1, 1) NOT NULL 定义表,则不应映射 id 列(除非您需要它,否则您需要使用 KeepIdentity SqlBulkCopyOption )跨度>
        猜你喜欢
        • 2018-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-20
        • 1970-01-01
        • 2010-11-05
        • 1970-01-01
        • 2012-06-21
        相关资源
        最近更新 更多