本例使用SqlServer

第一种方式结果放入Memo控件,,需要引用SynCommons, SynDB, SynOleDb;

procedure TForm1.Button1Click(Sender: TObject);
var
DbConn: TOleDBMSSQLConnectionProperties;
strSql: string;
rows: ISQLDBRows;begin
DbConn := TOleDBMSSQLConnectionProperties.Create('127.0.0.1', 'ReportServer', 'sa', 'Sa123');
strSql := 'SELECT r.RoleName, r.Description FROM Roles AS r';
rows := DbConn.ExecuteInlined(strSql, True);
if rows <> nil then
begin
memo1.Clear;
memo1.Lines.BeginUpdate;
while rows.Step() do
begin
Memo1.Lines.Add(rows.ColumnString('RoleName') + '-' + rows.ColumnString('Description'));
end;
end;
Memo1.Lines.EndUpdate;
end;

第二种方式,返回数据集到DBGrid控件,需要引用SynCommons, SynDB, SynOleDb, SynDBMidasVCL;

procedure TForm1.Button2Click(Sender: TObject);
var
DbConn: TOleDBMSSQLConnectionProperties;
ds: TSynDBDataSet;
begin
DbConn := TOleDBMSSQLConnectionProperties.Create('127.0.0.1', 'ReportServer', 'sa', 'Sa123');
ds := TSynDBDataSet.Create(nil);
ds.Connection := DbConn;
ds.CommandText := 'SELECT r.RoleName, r.Description FROM Roles AS r';
ds.Open;
DataSource1.DataSet := ds;
//ds不能在这里释放不然结果就不显示了
end;

两种方式执行结果

mORMot学习笔记2-2种方式查询数据-LMLPHP

05-24 06:21