描述
本示例演示了使用ADO来实现连接数据库。该示例要在窗体上放置一个TDBGrid。
代码
procedure TForm2.FormCreate(Sender: TObject);
const
{ 连接字符串 }
ConnString =
'Provider=SQLOLEDB.1;Persist Security Info=False;' +
'User ID=%s;Password=%s;Data Source=%s;Use Procedure for Prepare=1;' +
'Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;'+
'Tag with column collation when possible=False';
{SQL查询语句}
SQLStr = 'SELECT * FROM customer WHERE customer_id = :AnId;';
{用户访问权}
UserName = 'db_user_name';
PassWord = 'db_pass_word';
Server = 'my.db.server';
var
ADOConn : TADOConnection;
ADOQuery : TADOQuery;
DataSrc : TDataSource;
Param : TParameter;
begin
{ 创建ADO连接. }
ADOConn := TADOConnection.Create(Self);
{ 设置提供程序引擎 }
{ 设置连接字符串. }
ADOConn.ConnectionString := Format(ConnString,
[UserName, PassWord, Server]);
{ 禁用登录提示 }
ADOConn.LoginPrompt := False;
try
ADOConn.Connected := True;
except
on e: EADOError do
begin
MessageDlg('Error while connecting', mtError,
[mbOK], 0);
Exit;
end;
end;
{ 创建查询. }
ADOQuery := TADOQuery.Create(Self);
ADOQuery.Connection := ADOConn;
ADOQuery.SQL.Add(SQLStr);
{ 更新从SQL查询参数: AnId. }
Param := ADOQuery.Parameters.ParamByName('AnId');
Param.DataType := ftInteger;
Param.Value := 1;
{ 将查询设置为True,“将会提高性能” }
ADOQuery.Prepared := true;
try
ADOQuery.Active := True;
except
on e: EADOError do
begin
MessageDlg('Error while doing query', mtError,
[mbOK], 0);
Exit;
end;
end;
{ 创建数据源. }
DataSrc := TDataSource.Create(Self);
DataSrc.DataSet := ADOQuery;
DataSrc.Enabled := true;
{ 最后,初始化网格. }
DBGrid1.DataSource := DataSrc;
end;