65.9K
CodeProject 正在变化。 阅读更多。
Home

导入 CSV 数据并将其保存在数据库中

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.45/5 (53投票s)

2005年8月25日

2分钟阅读

viewsIcon

814123

downloadIcon

28253

本文介绍如何导入 CSV 数据并将其存储在数据库中。

引言

如今,在应用程序中拥有读取 CSV 数据的功能很常见。我当前的项目需要一个这样的功能。即使经过长时间的搜索,我也无法找到一个能够满足我的要求的。但在进行了大量的研究之后,我提出了以下工具。CSV 文件代表逗号分隔值文件。它们是带有逗号分隔值的常见文本文件。虽然默认分隔符是逗号 (,),但我们可以将其他字符指定为分隔符,例如分号 (;)、冒号 (:)、星号 (*)。但是您不能将双引号 (") 指定为分隔符。我使用了 Microsoft 文本驱动程序来读取 CSV 数据。您必须使用 ODBC 连接来访问 CSV 数据。您可以创建一个 DSN 或使用连接字符串。如果创建 DSN,schema.ini 文件将在所有 CSV 文件所在的文件夹中自动创建。但是如果使用连接字符串,则必须自己创建 schema.ini 文件。我们将看到后一种方法。

Schema.ini 文件 (文本文件驱动程序)

当使用文本驱动程序时,文本文件的格式是通过使用架构信息文件来确定的。架构信息文件始终命名为 schema.ini,并且始终与文本数据源保存在同一目录中,它为 IISAM 提供了有关文件的一般格式、列名和数据类型信息以及许多其他数据特征的信息。

使用演示应用程序

为了成功运行该应用程序,您需要 Test.csv 文件和一个包含三列的数据库表。但是所有这些都在演示应用程序中提供。所以您不必担心。按照以下步骤运行演示应用程序

  1. 首先运行 DBI.exe 应用程序。
  2. 将出现如下所示的屏幕。
  3. 填写所需的详细信息,然后单击“安装”按钮。
  4. 确保在“D:”驱动器中创建一个名为“Test”的文件夹,其中包含 Test.csv 文件。
  5. 现在运行我们的主要应用程序,即 FinalCSVReader.exe
  6. 保持默认文件夹和文件路径不变。
  7. 首先单击“导入 CSV 数据”以导入 CSV 数据。
  8. 现在单击“保存”,将数据保存到数据库中。

使用源代码

下面讨论一些重要的代码部分

创建 schema.ini

这是一个函数 writeSchema()。它动态地创建 schema.ini 文件。

/*Schema.ini File (Text File Driver)

 When the Text driver is used, the format of the
 text file is determined by using a schema information
 file. The schema information file, which is always named
 Schema.ini and always kept in the same directory as the
 text data source, provides the IISAM with information
 about the general format of the file, the column name
 and data type information, and a number of other data 
 characteristics*/

private void writeSchema()
{
 try    
    {
        FileStream fsOutput = 
             new FileStream (txtCSVFolderPath.Text+"\\schema.ini", 
                                 FileMode.Create, FileAccess.Write);
        StreamWriter srOutput = new StreamWriter (fsOutput);
        string s1, s2, s3,s4,s5;
        s1="["+strCSVFile+"]";
        s2="ColNameHeader="+bolColName.ToString ();
        s3="Format="+strFormat;
        s4="MaxScanRows=25";
        s5="CharacterSet=OEM";
        srOutput.WriteLine(s1.ToString()+'\n'+s2.ToString()+
                                    '\n'+s3.ToString()+'\n'+
                                    s4.ToString()+'\n'+s5.ToString());
        srOutput.Close ();
        fsOutput.Close ();                    
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
    }

用于导入 CSV 数据的函数

此函数 ConnectCSV (string filetable).csv 文件名作为参数,并返回包含导入数据的数据集。

public DataSet ConnectCSV (string filetable)
{
  DataSet ds = new DataSet ();
  try
   {        
       /* You can get connected to driver either by using
       DSN or connection string. Create a connection string
       as below, if you want to use DSN less connection.
       The DBQ attribute sets the path of directory which 
       contains CSV files*/

       string strConnString=
             "Driver={Microsoft Text Driver (*.txt;*.csv)};
             Dbq="+txtCSVFolderPath.Text.Trim()+";
             Extensions=asc,csv,tab,txt;
             Persist Security Info=False";

       string sql_select;                                
       System.Data.Odbc.OdbcConnection conn;        
        
       //Create connection to CSV file
       conn = new System.Data.Odbc.OdbcConnection(
                                    strConnString.Trim ());

       // For creating a connection using DSN, use following line
       //conn = new System.Data.Odbc.OdbcConnection(DSN="MyDSN");
    
       //Open the connection 
       conn.Open ();
       //Fetch records from CSV
       sql_select="select * from ["+ filetable +"]";
                
       obj_oledb_da=new System.Data.Odbc.OdbcDataAdapter(
                                                sql_select,conn);
       //Fill dataset with the records from CSV file
       obj_oledb_da.Fill(ds,"Stocks");
                
       //Set the datagrid properties
                
       dGridCSVdata.DataSource=ds;
       dGridCSVdata.DataMember="Stocks";
       //Close Connection to CSV file
       conn.Close ();                
   }
   catch (Exception e) //Error
   {
       MessageBox.Show (e.Message);
   }
   return ds;
}

用于插入数据的代码

这是写在按钮的点击事件 btnUpload_Click 中的代码。它实际上是将数据插入到数据库中。

private void btnUpload_Click(object sender, 
                                System.EventArgs e)
{
 try
  {
    // Create an SQL Connection
    // You can use actual connection 
    // string instead of ReadConFile()

    SqlConnection  con1=
         new SqlConnection(ReadConFile().Trim());
    SqlCommand cmd = new SqlCommand();
    SqlCommand cmd1 = new SqlCommand();

    // Create Dataset                    
    DataSet da = new DataSet();

    /* To actually fill the dataset,
    Call the function ImportCSV and   assign 
    the returned dataset to new dataset as below */

    da=this.ConnectCSV(strCSVFile);    

    /* Now we will collect data from data table
    and insert it into database one by one.
    Initially there will be no data in database 
    so we will insert data in first two columns 
    and after that we will update data in same row
    for remaining columns. The logic is simple.
    'i' represents rows while 'j' represents columns*/

    cmd.Connection=con1;
    cmd.CommandType=CommandType.Text;
    cmd1.Connection=con1;
    cmd1.CommandType=CommandType.Text;
                    
    con1.Open();
    for(int i=0;i<=da.Tables["Stocks"].Rows.Count-1;i++)
    {                        
      for(int j=1;j<=da.Tables["Stocks"].Columns.Count-1;j++)
      {
        cmd.CommandText= 
          "Insert  into Test(srno,
             "+da.Tables["Stocks"].Columns[0].ColumnName.Trim()+")
          values("+(i+1)+",
             '"+da.Tables["Stocks"].Rows[i].ItemArray.GetValue(0)+"')";
        
        /* For UPDATE statement, in where clause you
        need some unique row identifier. We are using 
        ‘srno’ in WHERE clause. */

        cmd1.CommandText=
          "Update Test set "
              +da.Tables["Stocks"].Columns[j].ColumnName.Trim()+"
              = '"+da.Tables["Stocks"].Rows[i].ItemArray.GetValue(j)+
          "' where srno ="+(i+1);                            
        cmd.ExecuteNonQuery();
        cmd1.ExecuteNonQuery();                            
      }
    }
    con1.Close();
  }
  catch(Exception ex)
  {
      MessageBox.Show(ex.Message);
  }
  finally
  {
      btnUpload.Enabled=false;
  }
}
© . All rights reserved.