EM数据包按规则更新

//delphi

unit emCopy;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ADODB, DB, StdCtrls, ExtCtrls;

type
  TForm1 = class(TForm)
    ADOConnection1: TADOConnection;
    ADOQuery1: TADOQuery;
    ListBox1: TListBox;
    ADOQuery2: TADOQuery;
    ADOQuery3: TADOQuery;
    Button1: TButton;
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

//声明变量
var
 sourceDir,targetDir,finalDir,finalDir1,filename,fileSeq : string;
    i ,  maxId , maxTmp : integer;
    subdir : tstrings;
    searchRec,FileRec: TsearchRec;

var
    j ,k , l,beginpos,endpos : integer  ;

var
  NewFileName,copystat: string;
  NewFile: TFileStream;
  OldFile: TFileStream;

//校验目录名
function IsValidDir(SearchRec:TSearchRec):Boolean;
begin
if (SearchRec.Attr=16) and
(SearchRec.Name<>'.') and
(SearchRec.Name<>'..') then
Result:=True
else
Result:=False;
end;

function IsValidFile(SearchRec:TSearchRec):Boolean;
begin
if (SearchRec.Name<>'.') and
(SearchRec.Name<>'..') then
Result:=True
else
Result:=False;
end;

 

procedure TForm1.FormCreate(Sender: TObject);
begin
    listbox1.Items.Add(DateTimeToStr(Now));
    listbox1.Items.Add('从库中读取目录信息...');
    try
        adoquery1.Open ;
        for i := 0 to adoquery1.RecordCount -1 do
        begin
            sourceDir := adoquery1.Fields[0].AsString;
            targetDir := adoquery1.Fields[1].AsString;
            listbox1.Items.Add('  源目录名是' + sourceDir);
            listbox1.Items.Add('  目标目录名是' + targetDir);

        end;
        adoquery1.Close;

        if DirectoryExists(sourceDir) and DirectoryExists(targetDir) then
        begin
            listbox1.Items.Add('源目录和目标目录检查完毕!');
            listbox1.Items.Add('--------------------------');
            subdir := TStringList.Create;
            if (FindFirst(sourceDir+'\*.*',faDirectory,searchRec)=0) then
            begin
                if IsValidDir(SearchRec) then
                begin
//                    FileList(SearchRec);
                end;
            end;
            while (FindNext(SearchRec) = 0) do
            begin
                if IsValidDir(SearchRec) then
                begin 
                    Form1.listbox1.Items.Add('正在处理'+SearchRec.Name+'餐厅数据...');
                    finalDir1 := sourceDir+'\'+SearchRec.Name+'\Send\';
                    finalDir := finalDir1 + '*.*' ;

                    //检查库中是否有餐厅记录,无则添加
                    listbox1.Items.Add('  正在从库中读出已有数据...');
                    Form1.ADOQuery2.SQL.Text :=  'select count(*) from copyinfo where StoreName = '''+SearchRec.Name+'''';
                    Form1.ADOQuery2.Open;
                    if (Form1.ADOQuery2.Fields[0].AsInteger = 0) then
                    begin
                        ADOQuery3.SQL.Text := 'insert into copyinfo values('''+SearchRec.Name+''',0,date(),''0'')';
                        ADOQuery3.ExecSQL;
                        ADOQuery3.Close;
                    end
                    else
                    begin
                    end;
                    Form1.ADOQuery2.Close;

                    //取出序列值
                    ADOQuery2.SQL.Text := 'select lastid from copyinfo where storename = ''' + SearchRec.Name + '''';
                    ADOQuery2.Open;
                    maxID := ADOQuery2.Fields[0].AsInteger;
                    ADOQuery2.Close;
                    listbox1.Items.Add('  '+SearchRec.Name+'餐厅已拷贝数据的最大编号为'+ inttostr(maxid));

                    //一个个取出文件
                    maxTmp := maxID ;

                    if (FindFirst(finalDir, faAnyFile, FileRec)=0) then
                    begin

                    end;
                    while (FindNext(FileRec) = 0) do
                    begin
                        copystat := '0' ;
                        if IsValidFile(FileRec) then
                        begin

                            fileseq := '';
                            filename := FileRec.Name ;
                            k := Length(FileRec.Name);
                            for j := 1 to k do
                            begin
                                if filename[j] = 'P' then
                                begin
                                    if j <> k-1 then
                                    begin
                                        beginpos := j +1 ;
                                    end;
                                end;
                                if filename[j] = '.' then
                                begin
                                    endpos := j -1  ;
                                end;
                            end;

                            //获得文件的编号
                            for l := beginpos to endpos do
                            begin
                                fileseq := fileseq + filename[l] ;
                            end;

                            if strtoint(fileseq) > maxID then
                            begin
                                listbox1.Items.Add('  正在拷贝'+FileRec.Name+' ...');
                                NewFileName := targetdir+ '\' + FileRec.Name ;
                                OldFile := TFileStream.Create(finalDir1+FileRec.Name, fmOpenRead);
                                try
                                    NewFile := TFileStream.Create(NewFileName, fmCreate);
                                    try
                                        NewFile.CopyFrom(OldFile, OldFile.Size);
                                        FreeAndNil(NewFile);
                                    except
                                        copystat := '11' ;
                                    end;
                                    FreeAndNil(OldFile);
                                except
                                    copystat := '12';
                                    listbox1.items.Add('  拷贝失败!');                                     
                                end;
                                if strtoint(fileseq) > maxTmp then
                                begin
                                    maxTmp := strtoint(fileseq) ;
                                end;
                                ADOQuery3.SQL.Text := 'insert into logs(storename,copydate,copytime,filename,status) values (''' + SearchRec.Name + ''',date(),time(),'''+FileRec.Name +''','''+copystat+''')' ;
                                ADOQuery3.ExecSQL ;
                                ADOQuery3.Close ;
                            end;
                            ADOQuery3.SQL.Text := 'update copyinfo set lastid = '+ inttostr(maxTmp) + ' where storename = ''' + SearchRec.Name + '''' ;
                            ADOQuery3.ExecSQL ;
                            ADOQuery3.Close ;

                        end;
                    end;
                    FindClose(FileRec);

                    listbox1.Items.Add(SearchRec.Name+'餐厅数据处理完毕!');
                    listbox1.Items.Add('--------------------------');

                end;
            end;

            FindClose(SearchRec);

        end
        else
        begin
            listbox1.Items.Add('  源目录或目标目录不存在!');
        end;

    except
       listbox1.Items.Add('无法从库中读取目录信息!');
    end;
listbox1.Items.Add('更详细的日志信息清查询emCopy.mdb数据库中logs表!');
listbox1.Items.SaveToFile('.\emCopy.log');

end;

procedure TForm1.Button1Click(Sender: TObject);
begin
    Form1.Close;
end;

end.


//c#

using System;
using System.Data;
using System.Data.OleDb;
using System.IO;

namespace emDataCopy
{
 /// <summary>
 /// Class1 的摘要说明。
 /// </summary>
   
 class Class1
 {
  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [STAThread]
  static void Main(string[] args)
  {
   //
   // TODO: 在此处添加代码以启动应用程序
   //
   string sourceDir = "";
   string targetDir = "";

   //建立文件连接
   OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data source= .\emCopy.mdb");
   OleDbCommand cmd = new OleDbCommand();
   
   //取目录名
   try
   {
    conn.Open();
    cmd.Connection = conn;
    cmd.CommandText = @"select * from dir";
    OleDbDataReader dr = cmd.ExecuteReader();
    while (dr.Read())
    {
     sourceDir = dr["sourcedir"].ToString();
     Console.WriteLine("文件的源目录为 "+sourceDir);
     targetDir = dr["targetdir"].ToString();
     Console.WriteLine("文件的目标路径为 "+targetDir);
    }
   }
   catch
   {
    
   }
   finally
   {
    if (conn.State != ConnectionState.Closed) conn.Close();
   }
   
   //设定文件根目录
   DirectoryInfo dbase = new DirectoryInfo(sourceDir);
   
   //获得所有文件夹
   foreach(DirectoryInfo di in dbase.GetDirectories()) //di->每一个目录,如xianxia
   {
    
    DirectoryInfo di_ = new DirectoryInfo(di.FullName + @"\Send"); //di_ ->包含send的路径,每个店的数据上传位置

    Console.WriteLine("正在读取"+di.Name+"餐厅的数据信息...");

    if (di_.GetFiles().Length > 0) //如果该目录下文件个数大于0
    {
     try
     {
      conn.Open();
      cmd.Connection =conn;
      cmd.CommandText = @"select count(*) from CopyInfo where StoreName = '"+di.Name+"'" ;
      if((int)cmd.ExecuteScalar() == 0) //如果数据库中无该店信息
      {
       int seqMax = 0;
       foreach(FileInfo fi in di_.GetFiles())
       {
        string fileName = fi.Name;
        int posP = fileName.IndexOf(@"P")+1;
        string fileName_ = fileName.Substring(posP);
        int posDot = fileName_.IndexOf(@".");
        int seq = Convert.ToInt32(fileName_.Substring(0,posDot));
        Console.WriteLine("正在拷贝"+di.Name+"餐厅的数据包"+fi.Name+" ...");
        
        File.Copy(fi.FullName,targetDir+@"\"+fi.Name);
        if (seq > seqMax)
        {
         seqMax = seq;
        }
       }
       //往库中增加信息
       Console.WriteLine(di.Name+"餐厅数据包的最大编号为"+seqMax.ToString()+",正在保存到数据库...");
       cmd.CommandText="insert into CopyInfo values ('" + di.Name + "'," + seqMax.ToString() + ",Date(),'0')";
       if (cmd.ExecuteNonQuery()==1)
       {
        Console.WriteLine(di.Name+"餐厅数据包信息保存成功!");
       }
       else
       {
        Console.WriteLine(di.Name+"餐厅数据包信息保存失败!");
       }
      }
      else //有该店信息
      {
       cmd.CommandText = @"select lastid from CopyInfo where StoreName = '" + di.Name + "'" ;
       int id = (int)cmd.ExecuteScalar();

       int seqMax = id;
       foreach(FileInfo fi in di_.GetFiles())
       {
        string fileName = fi.Name;
        int posP = fileName.IndexOf(@"P")+1;
        string fileName_ = fileName.Substring(posP);
        int posDot = fileName_.IndexOf(@".");
        int seq = Convert.ToInt32(fileName_.Substring(0,posDot));
        if (seq > id)
        {
         Console.WriteLine("正在拷贝"+di.Name+"餐厅的数据包"+fi.Name+" ...");

         File.Copy(fi.FullName,targetDir+@"\"+fi.Name);

         if (seq > seqMax)
         {
          seqMax = seq;
         }
        }
       }
       //更新库中信息
       Console.WriteLine(di.Name+"餐厅数据包的最大编号为"+seqMax.ToString()+",正在保存到数据库...");

       cmd.CommandText = @"update CopyInfo set lastid = " + seqMax.ToString() + @",copyDate_ = Date() where StoreName = '" + di.Name + "'";
       if (cmd.ExecuteNonQuery()==1)
       {
        Console.WriteLine(di.Name+"餐厅数据包信息保存成功!");
       }
       else
       {
        Console.WriteLine(di.Name+"餐厅数据包信息保存失败!");
       }
      }
     }
     catch{}
     finally
     {
      if (conn.State != ConnectionState.Closed) conn.Close();
     }
    }
    else
    {
     Console.WriteLine(di.Name+"餐厅没有数据信息");
    }
   }
  }
 }
}

你可能感兴趣的:(数据)