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; TotalNum,recNum,loopNum: Integer; fetchNum: Integer; 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; //连接数据源 // recNum:=0; fetchNum:=1000; while True do begin application.ProcessMessages ; inc(loopNum); inc(RecNum); with ADOQuery1 do //用ADO组件连接数据表 begin close; SQL.Clear; SQL.Add('Select objid, title,auxinfo,content from ctdsb2015_objs_1 where objid<='+(inttostr(fetchNum+RecNum-1))+' and objid>='+inttostr(RecNum)); //使用SQL语句查询数据表中的内容 open; end; ADOQuery1.Active := True; // TotalNum:=ADOQuery1.RecordCount;//1000 RecNum:=fetchNum+RecNum-1; // showmessage(inttostr(TotalNum)); ADOQuery1.First; richEdit1.Lines.BeginUpdate; while Not ADOQuery1.Eof do begin application.ProcessMessages ; 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; if loopNum=3 then break; end;//while true end // DataSource1.DataSet := ADOQuery1; // DBGrid1.DataSource := DataSource1; showmessage('ok'); end; end.