trueideal

C# CSV文件导入数据库

做CSV导入数据库,一般是采用逐行读取,数据连接读取,再有这个通过引用Microsoft.VisualBasic.FileIO.TextFieldParser

其它方法我没试过,有朋友可以提示一下,非常感谢。逐行读取方法比较傻,数据连接读取效率高,通过TextFileParser这个方法比较特殊吧,今天刚发现,感觉不错。

1.通过数据连接读取

 1:  private void button1_Click(object sender, EventArgs e)
 2:  {
 3:      subImportCsv_Dataset("f:\\", "jjj.csv");
 4:  }
 5:  public void subImportCsv_Dataset(string filePath, string fileName)
 6:  {
 7:      string strConn = @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=";
 8:      strConn += filePath;//这个地方只需要目录就可以了                                                      
 9:      strConn += ";Extensions=asc,csv,tab,txt;";
10:      OdbcConnection objConn = new OdbcConnection(strConn);
11:      DataSet ds = new DataSet();
12:      try
13:      {
14:          string strSQL = "select * from " + fileName;//文件名,不要带目录
15:          OdbcDataAdapter da = new OdbcDataAdapter(strSQL, objConn);
16:          da.Fill(ds);
17:          //开始导入数据库
18:      }
19:      catch (Exception ex)
20:      {
21:          throw ex;
22:      }
23:  }

 

2.通过TextFileParser读取

 1:  private void subImportCSV_FileIo(string strFile)
 2:  {
 3:      Microsoft.VisualBasic.FileIO.TextFieldParser TF = new Microsoft.VisualBasic.FileIO.TextFieldParser(strFile, Encoding.GetEncoding("GB2312"));
 4:      TF.Delimiters = new string[] { "," }; //设置分隔符
 5:      string[] strLine;
 6:      while (!TF.EndOfData)
 7:      {
 8:          try
 9:          {
10:              strLine = TF.ReadFields();
11:              //开始导入数据库,这个地方要排除行头
12:          }
13:          catch
14:          {
15:          }
16:      }
17:      TF.Close();
18:  }

posted on 2010-03-05 18:09  trueideal  阅读(2978)  评论(7编辑  收藏  举报

导航