delphi通过TADOConnection组件直接连接MSSQL数据库并读写数据。

Posted 游子日月长

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了delphi通过TADOConnection组件直接连接MSSQL数据库并读写数据。相关的知识,希望对你有一定的参考价值。

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Data.Win.ADODB, Vcl.StdCtrls,
  Vcl.Grids, Vcl.DBGrids, Vcl.ComCtrls;

type
  TForm1 = class(TForm)
    ADOConnection1: TADOConnection;
    Button1: TButton;
    ADOQuery1: TADOQuery;
    DataSource1: TDataSource;
    DBGrid1: TDBGrid;
    Memo1: TMemo;
    Memo2: TMemo;
    RichEdit1: TRichEdit;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
  sObjId,sMemo: string;
  sTitle: string;
  sauxinfo: string;
begin
//  Initial Catalog  数据库名称
//  Data Source   服务器名称或服务器IP
    ADOConnection1.ConnectionString := ‘Provider=SQLOLEDB.1;Password=admindkl;Persist Security Info=True;User ID=sa;Initial Catalog=infobase;Data Source=127.0.0.1‘;    //连接指定的数据库
    ADOConnection1.LoginPrompt := False;
    ADOConnection1.Connected := True;


    ADOQuery1.Connection := ADOConnection1;    //连接数据源
    with ADOQuery1 do    //用ADO组件连接数据表
    begin
        close;
        SQL.Clear;
        SQL.Add(‘Select objid, title,auxinfo,content from ctdsb2001_objs_1 where objid<=11000 and objid>=10000‘);    //使用SQL语句查询数据表中的内容
        open;
    end;
    ADOQuery1.Active := True;

   // showmessage(inttostr(ADOQuery1.RecordCount));

   { ADOQuery1.First;
    ADOQuery1.Next;
    Memo1.Text:= ADOQuery1.FieldByName(‘title‘).AsString;
    Memo2.Text:= pchar(ADOQuery1.FieldByName(‘content‘).AsWideString);
   }

    richEdit1.Lines.BeginUpdate;
    while Not  ADOQuery1.Eof do
    begin
         application.ProcessMessages ;
     // Memo1.Text:= pchar(ADOQuery1.FieldByName(‘content‘).AsWideString);
       sObjId:=ADOQuery1.FieldByName(‘objid‘).AsString;
       sTitle:=ADOQuery1.FieldByName(‘title‘).AsString;

      sauxinfo:=ADOQuery1.FieldByName(‘auxinfo‘).AsString;

       sMemo:=pchar(ADOQuery1.FieldByName(‘content‘).AsWideString);



       richEdit1.Lines.Add(sObjId+‘ === ‘+sTitle+‘ === ‘+sauxinfo+‘ === ‘+sMemo);

       ADOQuery1.Next;
       //break;
    end;

    richEdit1.Lines.EndUpdate;






    DataSource1.DataSet := ADOQuery1;
    DBGrid1.DataSource := DataSource1;



 //   ADOQuery1.RecordCount   //总记录数












    showmessage(‘ok‘);




end;

end.

  

以上是关于delphi通过TADOConnection组件直接连接MSSQL数据库并读写数据。的主要内容,如果未能解决你的问题,请参考以下文章

Delphi 的 TADOConnection 线程安全吗?

TADOConnection和TADQuery组件连接访问数据库总结

delphi线程

Delphi XE2 数据模块只需要数据库组件?

请问 Delphi 2010中怎么使用(安装)Sqlite数据库?

delphi 线程教学第四节:多线程类的改进