是否有可能分享DataSnap服务器和客户端之间的数据库连接?
我想在客户端执行动态SQL和收到成效。
是否有可能分享DataSnap服务器和客户端之间的数据库连接?
我想在客户端执行动态SQL和收到成效。
我发现2种方式在客户端执行动态SQL
1)使用DbxConnection(dbExpress的)
// Server code
function TServerMethods1.GetConnection: TDbxConnection;
begin
Result := DBConnection.DBXConnection;
end;
//Client code
dbxConnection := ServerMethods.GetConnection;
command := dbxConnection.CreateCommand;
command.Text := 'SELECT COUNT(1) FROM clients WHERE name LIKE :name';
param := com.CreateParameter;
param.Name := 'name';
param.DataType := TDBXDataTypes.WideStringType;
param.Value.SetString('%name%');
command.Parameters.AddParameter(param);
reader := command.ExecuteQuery;
reader.Next; // to Fetch row
ShowMessage(reader.Value[0].AsString);
2)使用的数据集的后代
服务器端组件
ServerMethods类必须TDSServerModule后裔
客户端组件
代码来执行查询
CDS.Close; // TClientDataSet
CDS.CommandText := 'SELECT COUNT(*) FROM clients WHERE name LIKE :name';
CDS.Params.ParamByName('name').AsString := '%name%';
CDS.Open;
ShowMessage(CDS.Fields[0].AsString);
服务器端代码:
MainMethods.pas
TMainMethods = class(TDSServerModule)
PgQuery: TPgQuery;
PgQueryProvider: TDataSetProvider;
PgConnection: TPgConnection;
end;
MainMethods.dfm
object MainMethods: TMainMethods
Height = 248
Width = 440
object PgConnection: TPgConnection
Left = 200
Top = 32
...
end
object PgQuery: TPgQuery
Connection: PgConnection
Left = 32
Top = 24
end
object PgQueryProvider: TDataSetProvider
DataSet = PgQuery
Options = [poAllowCommandText, poUseQuoteChar]
Left = 120
Top = 24
end
end
客户端代码:
client.pas
TVerusClient = class(TDataModule)
dbxVerusConnection: TSQLConnection;
dbxSqlConnectionProvider: TDSProviderConnection;
cdsSqlDataSet: TClientDataSet;
end;
client.dfm
object VerusClient: TVerusClient
Height = 271
Width = 415
object dbxVerusConnection: TSQLConnection
DriverName = 'DataSnap'
LoginPrompt = False
...
end
object dbxSqlConnectionProvider: TDSProviderConnection
ServerClassName = 'TMainMethods'
SQLConnection = dbxVerusConnection
Left = 176
Top = 32
end
object cdsSqlDataSet: TClientDataSet
ProviderName = 'PgQueryProvider'
RemoteServer = dbxSqlConnectionProvider
Left = 176
Top = 104
end
end
为的DataSnap(多级)应用程序的主要目标是security.You不能共享对象(连接,资源)直接(原生)在远程模式,但你可以在会话中更改数据集的SQL。 但它并不安全。
// Server Code
procedure TMyServerMethod.ChangeSQL(ASQL:string); // insecure
begin
AdoQuery1.Active:=false;
AdoQuery1.SQL.Text:=ASQL; // AdoQuery,DbxExpress,UniDAC,AnyDac,...
AdoQuery1.Active:=true;
end;
使用生成代理的客户端
// Client Code
procedure TForm1.Button1Click(Sender:TObject);
begin
Proxy.ChangeSQL('select * from custom_table');// but it is insecure
// loading remote datasets
end;