使用FDBatchMove导入TXT,CSV文件到数据库

void __fastcall TForm1::Button3Click(TObject *Sender)
{
//FDConnection1->FetchOptions->RecordCountMode << cmTotal;
       if (FDConnection1->Connected == true) {
				FDConnection1->Connected = false;

				}
			FDConnection1->Params->Clear();
			FDConnection1->Params->Add("DriverID=SQLite");
			FDConnection1->Params->Add("Database=New1.sdb");
			FDConnection1->Connected = true;

			FDCommand1->Connection = FDConnection1;
			FDCommand1->CommandText->Clear();
			FDCommand1->CommandText->Text = "DELETE FROM tablename";
			 FDCommand1->Active = True;

			 FDTable1->Connection=FDConnection1;
			 FDTable1->TableName="tablename";
			  FDTable1->Active=true;

	OpenDialog1->Title = "打开文本文件";
	OpenDialog1->Filter = "文本文件(*.csv)|*.csv;*.txt";

	if (OpenDialog1->Execute())
	{ // GuessFormat();
		Memo1->Lines->Add(" 导入开始  ");
		FDBatchMoveTextReader1->FileName = OpenDialog1->FileName;
		FDBatchMoveTextReader1->DataDef->Delimiter = ',';
		 FDBatchMoveTextReader1->DataDef->Separator = ',';
		FDBatchMoveTextReader1->DataDef->EndOfLine = elWindows;
		FDBatchMoveTextReader1->DataDef->RecordFormat = rfCustom;
		FDBatchMoveTextReader1->Encoding = ecANSI;
		 FDBatchMove1->Analyze<<taDelimSep<<taHeader<<taFormatSet;
		 FDBatchMove1->Reader= *FDBatchMoveTextReader1;
		 FDBatchMove1->Writer=  *FDBatchMoveDataSetWriter1;

		 String mm;
		FDBatchMoveTextReader1->DataDef->Fields->Clear();

		for (int i = 0; i <=18; i++) {        //设置文本文件的字段,字段个数必须一致
			mm = "a" + IntToStr(i);
			FDBatchMoveTextReader1->DataDef->Fields->Add()->FieldName = mm;
			Memo1->Lines->Add(mm);
			// FDBatchMoveTextReader1->DataDef->Fields->DataType=atString;
		}

		FDBatchMove1->Mappings->Clear();                   
 //设置导入对应关系,可以全部字段导入 ,这里是选择导入 。Mappings等号前面为FDTable1中的字段名称,后为文本文件中自己取的字段名
		FDBatchMove1->Mappings->Add("fh=a5");
		FDBatchMove1->Mappings->Add("bh=a1");
		FDBatchMove1->Mappings->Add("rz=a2");
		FDBatchMove1->Mappings->Add("zs=a13");
		//FDBatchMove1->Mappings->Add("dj=a16");

		 FDBatchMoveDataSetWriter1->DataSet=FDTable1;

	  //	  Memo1->Lines->Add(FDBatchMoveTextReader1->DataDef->Fields->Count);
		FDBatchMove1->Execute();

	  	

	}
	  Memo1->Lines->Add(String().sprintf(L"---- %s  中 %d 条记录已成功导入 ",FDTable1->TableName, FDBatchMove1->InsertCount));

}

 

上一篇:《SystemVerilog验证测试平台编写指南》学习笔记——功能覆盖率(三)


下一篇:MyBatis 流式查询