function FixFieldName(AFieldName: String): String;
begin
Result := StringReplace(AFieldName, ' ', '_', [rfReplaceAll]);
Result := StringReplace(Result, '(', '', [rfReplaceAll]);
Result := StringReplace(Result, ')', '', [rfReplaceAll]);
end;
procedure CopyToSqlite3(ADataset: TDataset; AFileName: String);
var
SQLiteConn: TSQLite3Connection;
Transaction: TSQLTransaction;
SQLQuery: TSQLQuery;
f: TField;
fieldName: String;
sql: String;
values: String;
bm: TBookmark;
begin
DeleteFile(AFileName);
{ Set up databse components }
SQLiteConn := TSQLite3Connection.Create(nil);
SQLiteConn.DatabaseName := AFileName;
Transaction := TSQLTransaction.Create(SQLiteConn);
Transaction.DataBase := SQLiteConn;
Transaction.Action := caCommit;
SQLiteConn.Open;
{ Create database and its fields }
sql := 'CREATE TABLE "data" (';
for f in ADataset.Fields do
begin
fieldName := FixFieldName(f.FieldName);
case f.DataType of
ftString: sql := sql + Format('"%s" VARCHAR(%d), ', [fieldName, f.Size]);
ftInteger: sql := sql + Format('"%s" INTEGER, ', [fieldName]);
ftFloat: sql := sql + Format('"%s" FLOAT, ', [fieldName]);
ftMemo: sql := sql + Format('"%s" VARCHAR, ', [fieldName]);
else raise Exception.Create('Field type not supported here.');
end;
end;
sql[Length(sql)-1] := ')';
SQLiteConn.ExecuteDirect(sql);
Transaction.Commit;
{ Add records as copy of dataset's records }
sql := 'INSERT INTO "data" (';
values := 'VALUES (';
for f in ADataset.Fields do
begin
fieldName := FixFieldName(f.FieldName);
sql := sql + Format('%s, ', [fieldName]);
values := values + Format(':%s, ', [fieldName]);
end;
sql[Length(sql)-1] := ')';
values[Length(values)-1] := ')';
sql := sql + values;
SQLQuery := TSQLQuery.Create(nil);
SQLQuery.DataBase := SQLiteConn;
SQLQuery.Transaction := Transaction;
SQLQuery.SQL.Add(sql);
bm := ADataset.GetBookmark;
try
ADataset.First;
while not ADataset.EoF do
begin
for f in ADataset.Fields do
begin
fieldName := FixFieldName(f.FieldName);
case f.DataType of
ftString: SQLQuery.ParamByName(fieldName).AsString := f.AsString;
ftInteger: SQLQuery.ParamByName(fieldName).AsInteger := f.AsInteger;
ftFloat: SQLQuery.ParamByName(fieldName).AsFloat := f.AsFloat;
ftMemo: SQLQuery.ParamByName(fieldName).Asstring := f.AsString;
end;
end;
SQLQuery.ExecSQL;
ADataset.Next;
end;
ADataset.GotoBookmark(bm);
finally
ADataset.FreeBookmark(bm);
end;
Transaction.Commit;
SQLQuery.Close;
SQLQuery.Free;
Transaction.Free;
SQLiteConn.Free;
end;