在Delphi中使用和加密Sqlite数据库

设置 TFDConnection 的两个链接参数: Password, NewPassword, 非常简单.

 const

  dbPath = 'D:SQLiteTest.db';

 

{建立加密数据库, 密码是 123456 }

procedure TForm1.FormCreate(Sender: TObject);

const

  strTable = 'CREATE TABLE MyTable(Id integer, Name string(10), Age byte)'; //Id, Name, Age 三个字段

begin

  if FileExists(dbPath) then DeleteFile(dbPath);

  FDConnection1.Params.Add('DriverID=SQLite');

  FDConnection1.Params.Add('Database=' + dbPath);

  FDConnection1.Params.Add('Password=123456'); //相同与 Password=aes-256:mm123; aes-256 是默认的加密算法;

  //还有: aes-128,aes-192,aes-256, aes-ctr-128,aes-ctr-192,aes-ctr-256, aes-ecb-128,aes-ecb-192,aes-ecb-256

  //建表并输入测试数据

  FDConnection1.ExecSQL(strTable);

  FDConnection1.ExecSQL('INSERT INTO MyTable(Id, Name, Age) VALUES(:1, :2, :3)', [1, 'abc', 23]);

end;

 

{打开有密码的数据库}

procedure TForm1.Button1Click(Sender: TObject);

begin

  FDConnection1.Params.Clear;

  FDConnection1.Connected := False;

  FDConnection1.Params.Add('DriverID=SQLite');

  FDConnection1.Params.Add('Database=' + dbPath);

  FDConnection1.Params.Add('Password=mm123');

  FDConnection1.Connected := True;

  FDQuery1.Open('SELECT * FROM MyTable');

end;


{修改密码}

procedure TForm1.Button2Click(Sender: TObject);

begin

  FDConnection1.Params.Clear;

  FDConnection1.Connected := False; 

  FDConnection1.Params.Add('DriverID=SQLite');

  FDConnection1.Params.Add('Database=' + dbPath);

  FDConnection1.Params.Add('Password=mm123');

  FDConnection1.Params.Add('NewPassword=mm12345'); //新密码, 密码为空表示取消密码

  FDConnection1.Connected := True;

  FDConnection1.Connected := False;

end;

 

FireDAC 还提供了一个专用的加密控件 TFDSQLiteSecurity, 因为上面的方法足够方便了, 所以用处不大.

FDSQLiteSecurity1.DriverLink := FDPhysSQLiteDriverLink1;  //TFDSQLiteSecurity 和 FireDAC.Phys.SQLite 里的其他四个控件, 使用前都要先指定这个属性

FDSQLiteSecurity1.Database := dbPath;    //指定数据库路径

FDSQLiteSecurity1.Password := '123456';   //密码

FDSQLiteSecurity1.ToPassword := 'abcdef'; //新密码

FDSQLiteSecurity1.SetPassword;           //设置密码

FDSQLiteSecurity1.ChangePassword;        //修改密码

FDSQLiteSecurity1.RemovePassword;        //移除密码

通过 FireDAC 加密的 SQLite 与其它并不兼容.


 上一个     下一个