Delphi小例程

procedure TCSystemForm.saveSchoolInfo;
var
SchoolInfoThread: TSchoolInfoThread; // 此线程为自定义的处理相关操做的线程
begin
// 建立线程,并挂起(暂不执行Execute里的内容)
SchoolInfoThread := TSchoolInfoThread.Create(True);
// 线程执行完自动销毁
SchoolInfoThread.FreeOnTerminate := True;
// 指定线程结束后要运行的方法
SchoolInfoThread.OnTerminate := DlThreadTerminate;
// 唤醒线程,开始执行Execute里的内容
SchoolInfoThread.Start;

if not Assigned(CLoadingForm) then // CLoadingForm 为本身画的另一个等待窗口 里面用一个gif图片在那里转啊转 = =
CLoadingForm := TCLoadingForm.Create(Self);
CLoadingForm.ShowModal;
end;

{ 相关操做的线程结束后须要运行的处理函数 }
procedure TCSystemForm.DlThreadTerminate(Sender: TObject);
begin
if Assigned(CLoadingForm) then // 把提示窗口关闭
CLoadingForm.Close;
// 也能够再到这里添加其余的操做代码
end;html

 

(1).按下ctrl和其它键以后发生一事件。sql

 procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;shell

  Shift: TShiftState);数据库

    begincanvas

      if (ssCtrl in Shift) and (key =67) thenapp

         showmessage('keydown Ctrl+C');框架

    end;ide

(2).Dbgrid中用Enter键代替Tab键.函数

   procedure TForm1.DBGrid1KeyPress(Sender: TObject; var Key: Char);sqlserver

   begin

     if Key = #13 then

     if ActiveControl = DBGrid1 then

     begin

        TDBGrid(ActiveControl).SelectedIndex := TDBGrid(ActiveControl).SelectedIndex + 1;

        Key := #0;

     end;

   end;

(3).Dbgrid中选择多行发生一事件。

    procedure TForm1.Button1Click(Sender: TObject);

    var

    i:integer;

    bookmarklist:Tbookmarklist;

    bookmark:tbookmarkstr;

    begin

      bookmark:=adoquery1.Bookmark;

      bookmarklist:=dbgrid1.SelectedRows;

      try

      begin

        for i:=0 to bookmarklist.Count-1 do

        begin

          adoquery1.Bookmark:=bookmarklist[i];

          with adoquery1 do

          begin

            edit;

            fieldbyname('mdg').AsString:=edit2.Text;

            post;

          end;

        end;

      end;

      finally

      adoquery1.Bookmark:=bookmark;

      end;

    end;

(4).Form的一个出现效果。

    procedure TForm1.Button1Click(Sender: TObject);

    var

    r:thandle;

    i:integer;

    begin

      for i:=1 to trunc(width/1.414) do

      begin

        r:=CreateEllipticRgn(trunc(width/2)-i,trunc(height/2)-i,trunc(width/2)+i,trunc(height/2)+i);

        SetWindowRgn(handle,r,true);

        Application.ProcessMessages;

        sleep(1);

      end;

    end;

(5).用Enter代替Tab在编辑框中移动隹点。

    procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);

    begin

      if key=#13 then

        begin

          if not (Activecontrol is Tmemo) then

          begin

            key:=#0;

            keybd_event(vk_tab,mapvirtualkey(vk_tab,0),0,0);

          end;

        end;

    end;

(6).Progressbar加上色彩。

    const

    {$EXTERNALSYM PBS_MARQUEE}

    PBS_MARQUEE = 08;

    var

      Form1: TForm1;

    implementation

    {$R *.dfm}

    uses

    CommCtrl;

    procedure TForm1.Button1Click(Sender: TObject);

    begin

      // Set the Background color to teal

      Progressbar1.Brush.Color := clTeal;

      // Set bar color to yellow

      SendMessage(ProgressBar1.Handle, PBM_SETBARCOLOR, 0, clYellow);

    end;

(7).住点移动时编辑框色彩不一样。

    procedure TForm1.Edit1Enter(Sender: TObject);

    begin

      (sender as tedit).Color:=clred;

    end;

    procedure TForm1.Edit1Exit(Sender: TObject);

    begin

      (sender as tedit).Color:=clwhite;

    end;

(8).备份和恢复

    procedure TForm1.Button1Click(Sender: TObject);

    begin

      if OpenDialog1.Execute then

      begin

        try

          adoconnection1.Connected:=False;

          adoconnection1.ConnectionString:='Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=master;Data Source=FRIEND-YOFZKSCO;'+

          'Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=FRIEND-YOFZKSCO;Use Encryption for Data=False;Tag with column collation when possible=False';

          adoconnection1.Connected:=True;

          with adoQuery1 do

          begin

            Close;

            SQL.Clear;

            SQL.Add('Backup DataBase sfa to disk ='''+opendialog1.FileName+'''');

            ExecSQL;

          end;

        except

          ShowMessage('±?·Yê§°ü');

        Exit;

        end;

      end;

      Application.MessageBox('1§?2?ú£?êy?Y±?·Y3é1|','ìáê?',MB_OK + MB_ICONINFORMATION);

    end;

    procedure TForm1.Button2Click(Sender: TObject);

    begin

      if OpenDialog1.Execute then

      begin

        try

          adoconnection1.Connected:=false;

          adoconnection1.ConnectionString:='Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=master;Data Source=FRIEND-YOFZKSCO;'+

         'Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=FRIEND-YOFZKSCO;Use Encryption for Data=False;Tag with column collation when possible=False';

          adoconnection1.Connected:=true;

          with adoQuery1 do

          begin

            Close;

            SQL.Clear;

            SQL.Add('Restore DataBase sfa from disk ='''+opendialog1.FileName+'''');

            ExecSQL;

         end;

       except

         ShowMessage('???′ê§°ü');

         Exit;

       end;

     end;

     Application.MessageBox('1§?2?ú£?êy?Y???′3é1|','ìáê?',MB_OK + MB_ICONINFORMATION);

    end;

9).查找局域网上的sqlserver报务器。

 uses Comobj;

    procedure TForm1.Button1Click(Sender: TObject);

    var

    SQLServer:Variant;

    ServerList:Variant;

    i,nServers:integer;

    sRetValue:String;

    begin

      SQLServer := CreateOleObject('SQLDMO.Application');

      ServerList:= SQLServer.ListAvailableSQLServers;

      nServers:=ServerList.Count;

      for i := 1 to nservers do

      ListBox1.Items.Add(ServerList.Item(i));

      SQLServer:=NULL;

      serverList:=NULL;

    end;

(10).窗体打开时的淡入效果。

 procedure TForm1.FormCreate(Sender: TObject);

    begin

      AnimateWindow (Handle, 400, AW_CENTER);

    end;

(11).动态建立窗体。

    procedure TForm1.Button1Click(Sender: TObject);

    begin

      try

        form2:=Tform2.Create(self);

        form2.ShowModal;

      finally

        form2.Free;

      end;

    end;

    procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);

    begin

      action:=cafree;

    end;

    procedure TForm1.FormDestroy(Sender: TObject);

    begin

      form1:=nil;

    end;

(12).复制文件。

    procedure TForm1.Button1Click(Sender: TObject);

    begin

      try

      copyfileA(pchar('C:\AAA.txt'),pchar('D:\AAA.txt'),false);

      except

      showmessage('sfdsdf');

      end;

    end;

 

(13).复制文件夹。

    uses shellAPI;

    procedure TForm1.Button1Click(Sender: TObject);

    var

       lpFileOp: TSHFileOpStruct;

    begin

      with lpFileOp do

      begin

        Wnd:=Self.Handle;

        wfunc:=FO_COPY;

        pFrom:=pchar('C:\AAA');

        pTo:=pchar('D:\AAA');

        fFlags:=FOF_ALLOWUNDO;

        hNameMappings:=nil;

        lpszProgressTitle:=nil;

        fAnyOperationsAborted:=True;

     end;

     if SHFileOperation(lpFileOp)<>0 then

     ShowMessage('删除失败');

    end;

(14).改变Dbgrid的选定色。

    procedure TForm1.DBGrid1DrawDataCell(Sender: TObject; const Rect: TRect;

    Field: TField; State: TGridDrawState);

    begin

      if gdSelected in state then

      SetBkColor(dbgrid1.canvas.handle,clgreen)

      else

      setbkcolor(dbgrid1.canvas.handle,clwhite);

      dbgrid1.Canvas.TextRect(rect,0,0,field.AsString);

      dbgrid1.Canvas.Textout(rect.Left,rect.Top,field.AsString);

    end;

(15).检测系统是否已安装了ADO。

    uses registry;

    function Tform1.ADOInstalled:Boolean;

    var

    r:TRegistry;

    s:string;

    begin

      r := TRegistry.create;

      try

      with r do

      begin

        RootKey := HKEY_CLASSES_ROOT;

        OpenKey( '\ADODB.Connection\CurVer', false );

        s := ReadString('');

        if s <> '' then Result := True

        else Result := False;

        CloseKey;

      end;

      finally

       r.free;

      end;

    end;

    procedure TForm1.Button1Click(Sender: TObject);

    begin

     if ADOInstalled then showmessage('this computer has installed ADO');

    end;

(16).取利主机的ip地址。

    uses winsock;

    procedure TForm1.Button1Click(Sender: TObject);

    var

    IP:string;

    IPstr:String;

    buffer:array[1..32] of char;

    i:integer;

    WSData:TWSAdata;

    Host:PHostEnt;

    begin

      if WSAstartup(2,WSData)<>0 then

      begin

        showmessage('WS2_32.DLL3?ê??ˉê§°ü.');

        exit;

      end;

      try

        if GetHostname(@buffer[1],32)<>0 then

        begin

          showmessage('??óDμ?μ??÷?ú??.');

        exit;

      end;

      except

        showmessage('??óD3é1|·μ???÷?ú??');

        exit;

      end;

      Host:=GetHostbyname(@buffer[1]);

      if Host=nil then

      begin

        showmessage('IPμ??·?a??.');

        exit;

      end

      else

      begin

        edit2.Text:=Host.h_name;

        edit3.Text:=chr(host.h_addrtype+64);

        for i:=1 to 4 do

        begin

         IP:=inttostr(ord(host.h_addr^[i-1]));

         if i<4 then

         ipstr:=ipstr+IP+'.'

        else

         edit1.Text:=ipstr+ip;

        end;

       end;

       WSACleanup;

    end;

(17).取得计算机名。

    function tform1.get_name:string;

    var  ComputerName: PChar;  size: DWord;

    begin

        GetMem(ComputerName,255);

        size:=255;

        if GetComputerName(ComputerName,size)=False then

           result:=''

        else

           result:=ComputerName;

        FreeMem(ComputerName);

    end;

    procedure TForm1.Button1Click(Sender: TObject);

    begin

      label1.Caption:=get_name;

    end;

(18).取得硬盘序列号。

    function tform1.GetHDSerialNumber: LongInt;   

    {$IFDEF WIN32}

    var

      pdw : pDWord;

      mc, fl : dword;

    {$ENDIF}

    begin

      {$IfDef WIN32}

      New(pdw);

      GetVolumeInformation('c:\',nil,0,pdw,mc,fl,nil,0);

      Result := pdw^;

      dispose(pdw);

     {$ELSE}

      Result := GetWinFlags;

      {$ENDIF}

    end;

    procedure TForm1.Button1Click(Sender: TObject);

    begin

      edit1.Text:=inttostr(gethdserialnumber);

    end;

(19).限定光标移动范围。

    procedure TForm1.Button1Click(Sender: TObject);

    var

    rect1:trect;

    begin

      rect1:=button2.BoundsRect;

      mapwindowpoints(handle,0,rect1,2);

      clipcursor(@rect1);

    end;

    procedure TForm1.Button2Click(Sender: TObject);

    var

    screenrect:trect;

    begin

      screenrect:=rect(0,0,screen.Width,screen.Height);

      clipcursor(@screenrect);

    end;

(20).限制edit框只能输入数字。

    procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);

    begin

      if not (key in ['0'..'9','.',#8]) then

      begin

        key:=#0;

        Messagebeep(0);

      end;

    end;

(21).dbgrid中根据任一条件某一格变色。

    procedure TForm_main.DBGridEh1DrawColumnCell(Sender: TObject;

    const Rect: TRect; DataCol: Integer; Column: TColumnEh;

    State: TGridDrawState);

    begin

      if (trim(DataModule1.ADOQuery1.FieldByName('dczt').AsString)='OK') then

      begin

        if datacol=6 then

        begin

          DbGrideh1.Canvas.Brush.Color:=clGradientActiveCaption;

          DbGrideh1.DefaultDrawColumnCell(Rect,datacol,column,state);

       end;

      end;

    end;

(22).打开word文件。

    procedure TfjfsglForm.SpeedButton4Click(Sender: TObject);

    var

    MSWord: Variant;

    str:string;

    begin

      if trim(DataModule1.adoquery27.fieldbyname('fjmc').asstring)<>'' then

      begin

        str:=trim(DataModule1.ADOQuery27.fieldbyname('fjmc').AsString);

        MSWord:= CreateOLEObject('Word.Application');//

        MSWord.Documents.Open('d:\Program Files\Common Files\Sfa\'+str, True);//

        MSWord.Visible:=1;//

        str:='';

        MSWord.ActiveDocument.Range(0, 0);//

        MSWord.ActiveDocument.Range.InsertAfter(str);//?úWord?D???ó×?·?'Title'

        MSWord.ActiveDocument.Range.InsertParagraphAfter;

      end

      else

      showmessage('');

    end;

(23).word文件传入和传出数据库。

    uses IdGlobal;

    procedure TdjhyForm.SpeedButton2Click(Sender: TObject);

    var

    sfilename:string;

    function BlobContentTostring(const Filename:string):string;

    begin

      with Tfilestream.Create(filename,fmopenread)  do

      try

        setlength(result,size);

        read(pointer(result)^,size);

      finally

        free;

      end;

    end;

    begin

      if opendialog1.Execute then

      begin

        sfilename:=opendialog1.FileName;

        DataModule1.ADOQuery14.Edit;

        DataModule1.ADOQuery14.FieldByName('word').AsString:=blobcontenttostring(sfilename);

        DataModule1.ADOQuery14.Post;

      end;

    end;

    procedure TdjhyForm.SpeedButton1Click(Sender: TObject);

    var

    sfilename:string;

    bs:Tadoblobstream;

    begin

      bs:=Tadoblobstream.Create(TBLOBfield(DataModule1.ADOQuery14.FieldByName('word')),bmread);

      try

       sfilename:=extractfilepath(application.ExeName)+trim(DataModule1.adoquery14.fieldbyname('hybh').AsString);

        sfilename:=sfilename+'.'+'doc';

        bs.SaveToFile(sfilename);

        try

          djhyopenform:=Tdjhyopenform.Create(self);

          djhyopenform.olecontainer1.CreateObjectFromFile(sfilename,false);

          djhyopenform.OleContainer1.Iconic:=true;

          djhyopenform.ShowModal;

        finally

          djhyopenform.Free;

        end;

      finally

 

        bs.free;

 

      end;

 

    end;

 

(24).中文标题的提示框。

 

    procedure TdjhyForm.SpeedButton5Click(Sender: TObject);

 

    begin

 

      if Application.MessageBox('', Mb_YesNo + Mb_IconWarning) =Id_yes then DataModule1.ADOQuery14.Delete;

 

    end;

 

(25).运行一应用程序文件。

 

    WinExec('HH.EXE D:\Program files\common files\MyshipperCRM e-sales help\MyshipperCRM e-sales help.chm',SW_NORMAL);

 

回复人: MERRITTE(凌宇锋) ( ) 信誉:100  2004-2-12 21:35:19  得分:0

 

 

 

这是本人接触delphi半年来,的一些笔记。(共享)

 

×调用EXCLE打开文件。

USES SHELLAPI

Shellexecute(handle,nil,pchar('c:\报表.xls'),nil,nil,sw_shownormal);

 

◇[DELPHI]关于处理注册表

uses Registry;

var reg:Tregistry;

reg:=Tregistry.create;

reg.rootkey:='HKey_Current_User';

reg.openkey('Control Panel\Desktop',false);

reg.WriteString('Title Wallpaper','0');

reg.writeString('Wallpaper',filelistbox1.filename);

reg.closereg;

reg.free;

 

 

×报错函数

procedure ErrMsg(sMsg:String; sPrompt:String='出错信息');//出错信息显示框

begin

  Application.MessageBox(PChar(sMsg), PChar(sPrompt), MB_ICONERROR or MB_OK)

end;

×出错信息

    try

    except

      on E: Exception do begin

        ErrMsg(Format('登陆[%s]数据库失败,回退操做将失效;'#13#10, [Server]) + E.Message);

        Result := False;

      end;

    end;

 

×中文提示框

Application.MessageBox('没法打开指定文件', '提示', MB_OK);

 

×转换时间的函数

formatdatetime('yyyy"年"mm"月"dd"日"', UnccSysDate);UnccSysDate 为TDATATIME类型

 

×定死小数点后的位数

Format('%*.*n', [10, 2, FieldByName('syje').AsFloat]

 

×类型转换函数

  inttostr();    将数字转换为字符串

  Ord();  返回一个字符的序号(ASCII码)

  Char();       把一个整型数转化成相应序号的字符

  UpCase();   把小写转化为大写

 

 

×字符串处理函数

  concat();     与(+)功能相同,将多个字符串组合在一块儿

  copy();      会返回一个字符串中的子字符串

  delete();      在一个字符串中从一个指定位置起删除必定数字的字符()

  insert();      在一个字符串中插入一个字符串

  length();      返回字符串的长度

  pos();         返回一个子字符串在一个字符串中的位置

 

载入文件的实现方法

×var 

  ts:tstring;

  begin

  ts:tstinglist.creat;

  ts.loadfromfile('文件的绝对路径');   //调用文件

 

×文件夹操做

uses filectrl;

procedure ForceDirectorys(dir:string)

       //一次创建指定的多级文件夹

function DirectoryExists(Name: string): Boolean;

      // 指定文件夹是否存在

function SelectDirectory(var Directory: string; Options: TSelectDirOpts; HelpCtx: Longint):Boolean;

     // 打开一个选择文件夹的对话框(英文的)

 

 

×var mytextfile:textfile;              

begin assignfile(mytextfile,'mytextfile.exe');

reset(mytextfile);//rewrite()建立并打开文件(已有就覆盖),reset()以只读方式打开文件,append()以追加方式打开文件;

try  

       //能够加一句while nit eof(mytextfile) do;

       {

       //操做文件

       for i:=1 to 5 do

       begin s:='This is line #';

       writeln(mytextfile,s,i);//结果被建立的文件中包含 this is line # 1……this is line # 5

       //writeln()为往指定文件中写东西,还有readln(mytextfile,s,i)从指定的文件中读数据;

       end;

       }

       finally

       closefile(mytextfile);

       end;

end;

 

×edit只能接收数字

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);

begin

if ((Key < '0') or (Key > '9'))

then Key := Chr(0);

end;

 

×建立路径USES  FileCtrl;

if not DirectoryExists(ExtractFilePath(paramstr(0)) + 'ElectronicBill\') then

         CreateDir(ExtractFilePath(paramstr(0)) + 'ElectronicBill\');

fileexists();判断文件是否存在。

 

×选择一个路径  USES FileCtrl;

 SelectDirectory('请选择存储路径!', '个人电脑', sSavePath);         

 

回复人: Drate(小虫(Drate@163.com)) ( ) 信誉:156  2003-8-27 22:28:30  得分:10

 

呵呵,我这里找了一个

是CoolSlob写的,我顺便收了,有的时候感受还好用,就放上来吧:

 

{

功能描述:把DBGrid输出到Excel表格(支持多Sheet)

设计:CoolSlob

日期:2002-10-23

支持:CoolSlob@163.com

调用格式:CopyDbDataToExcel([DBGrid1, DBGrid2]);

}

procedure CopyDbDataToExcel(Args: array of const);

var

  iCount, jCount: Integer;

  XLApp: Variant;

  Sheet: Variant;

  I: Integer;

begin

  Screen.Cursor := crHourGlass;

  if not VarIsEmpty(XLApp) then

  begin

    XLApp.DisplayAlerts := False;

    XLApp.Quit;

    VarClear(XLApp);

  end;

 

  try

    XLApp := CreateOleObject('Excel.Application');

  except

    Screen.Cursor := crDefault;

    Exit;

  end;

 

  XLApp.WorkBooks.Add;

  XLApp.SheetsInNewWorkbook := High(Args) + 1;

 

  for I := Low(Args) to High(Args) do

  begin

    XLApp.WorkBooks[1].WorkSheets[I+1].Name := TDBGrid(Args[I].VObject).Name;

    Sheet := XLApp.Workbooks[1].WorkSheets[TDBGrid(Args[I].VObject).Name];

   

    if not TDBGrid(Args[I].VObject).DataSource.DataSet.Active then

    begin

      Screen.Cursor := crDefault;

      Exit;

    end;

 

    TDBGrid(Args[I].VObject).DataSource.DataSet.first;

    for iCount := 0 to TDBGrid(Args[I].VObject).Columns.Count - 1 do

      Sheet.Cells[1, iCount + 1] :=

          TDBGrid(Args[I].VObject).Columns.Items[iCount].Title.Caption;

         

    jCount := 1;

    while not TDBGrid(Args[I].VObject).DataSource.DataSet.Eof do

    begin

      for iCount := 0 to TDBGrid(Args[I].VObject).Columns.Count - 1 do

        Sheet.Cells[jCount + 1, iCount + 1] :=

            TDBGrid(Args[I].VObject).Columns.Items[iCount].Field.AsString;

           

      Inc(jCount);

      TDBGrid(Args[I].VObject).DataSource.DataSet.Next;

    end;

    XlApp.Visible := True;

  end;

  Screen.Cursor := crDefault;

end;

 

ADO.net 中数据库链接方式    carper(原做)

 

关键字     ADO.net 中数据库链接方式  

 

 

在MSDN中,.net的数据库链接字符串都有详细的说明,我这里以代码范例的方式罗列一些,具体的每一项表明的意义能够参看MSDN.

 

ADO.net 中数据库链接方式(微软提供)

 

微软提供了如下四种数据库链接方式:

System.Data.OleDb.OleDbConnection

System.Data.SqlClient.SqlConnection

System.Data.Odbc.OdbcConnection

System.Data.OracleClient.OracleConnection

下面咱们以范例的方式,来依次说明:

 

System.Data.SqlClient.SqlConnection

经常使用的一些链接字符串(C#代码):

 

SqlConnection conn

= new SqlConnection( "Server=(local);Integrated Security=SSPI;database=Pubs");

 

SqlConnection conn

= new SqlConnection("server=(local)\\NetSDK;database=pubs;Integrated Security=SSPI");

 

SqlConnection conn = new SqlConnection(

"Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;");

 

SqlConnection conn = new SqlConnection(

" data source=(local);initial catalog=xr;integrated security=SSPI;

persist security info=False;workstation id=XURUI;packet size=4096; ");

 

SqlConnection myConn  = new

System.Data.SqlClient.SqlConnection("Persist Security Info=False;Integrated

Security=SSPI;database=northwind;server=mySQLServer");

 

SqlConnection conn = new SqlConnection(

" uid=sa;pwd=passwords;initial catalog=pubs;data source=127.0.0.1;Connect Timeout=900");

 

更多字符串链接说明请看MSDN:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemDataSqlClientSqlConnectionClassConnectionStringTopic.asp

 

System.Data.OleDb.OleDbConnection

经常使用的一些链接字符串(C#代码):

 

OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\MyWeb\81\05\GrocerToGo.mdb");

 

OleDbConnection conn = new OleDbConnection(

@"Provider=Microsoft.Jet.OLEDB.4.0;Password=;

User ID=Admin;Data Source=grocertogo.mdb;");

 

OleDbConnection conn = new OleDbConnection(

"Provider=MSDAORA; Data Source=ORACLE8i7;Persist Security Info=False;Integrated Security=yes");

 

OleDbConnection conn = new OleDbConnection(

"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\bin\LocalAccess40.mdb");

 

OleDbConnection conn = new OleDbConnection(

"Provider=SQLOLEDB;Data Source=MySQLServer;Integrated Security=SSPI");

 

更多字符串链接说明请看MSDN:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemDataOleDbOleDbConnectionClassConnectionStringTopic.asp?frame=true

 

 

System.Data.OracleClient.OracleConnection

经常使用的一些链接字符串(C#代码):

 

OracleConnection myConn = new System.Data.OracleClient.OracleConnection(

"Data Source=Oracle8i;Integrated Security=yes");

 

 

 

更多字符串链接说明请看MSDN:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemDataOracleClientOracleConnectionClassConnectionStringTopic.asp?frame=true

 

 

System.Data.Odbc.OdbcConnection

经常使用的一些链接字符串(C#代码):

 

 

OdbcConnection conn = new OdbcConnection(

"Driver={SQL Server};Server=MyServer;Trusted_Connection=yes;Database=Northwind;");

 

OdbcConnection conn = new OdbcConnection(

"Driver={Microsoft ODBC for Oracle};Server=ORACLE8i7;

Persist Security Info=False;Trusted_Connection=yes");

 

OdbcConnection conn = new OdbcConnection(

"Driver={Microsoft Access Driver (*.mdb)};DBQ=c:\bin\nwind.mdb");

 

OdbcConnection conn = new OdbcConnection(

"Driver={Microsoft Excel Driver (*.xls)};DBQ=c:\bin\book1.xls");

 

 

OdbcConnection conn = new OdbcConnection(

"Driver={Microsoft Text Driver (*.txt; *.csv)};DBQ=c:\bin");

 

OdbcConnection conn = new OdbcConnection("DSN=dsnname");

 

更多字符串链接说明请看MSDN:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemDataOdbcOdbcConnectionClassConnectionStringTopic.asp?frame=true

 

 

其余厂商提供的数据库链接:

 

DB2Connection myConn = new IBM.Data.DB2.DB2Connection(

"DATABASE = SAMPLE;UID=<username>; PWD=<password>;");

 

DB2Connection myConn = new IBM.Data.DB2.DB2Connection("DATABASE = SAMPLE");

 

 

BdpConnection myConn = new Borland.Data.Provider.BdpConnection("assembly=Borl

and.Data.Mssql,Version=1.1.0.0,Culture=neutral,PublicKeyToken=91d62ebb5b0d1b1b;ve

ndorclient=sqloledb.dll;osauthentication=False;database=<database>;usernam

e=<user>;hostname=<host>;password=<password>;provider=MSSQL");

 

BdpConnection myConn = new Borland.Data.Provider.BdpConnection("assembly=Borl

and.Data.Db2,Version=1.1.0.0,Culture=neutral,PublicKeyToken=91d62ebb5b0d1b1b;ve

ndorclient=db2cli.dll;database=<database>;username=<user>;

password=<password>;provider=DB2");

 

 

Connection Pooling

 

 

在SQL Server、OLE DB和.NET框架结构中的Data Provider中,都提供了隐式的链接池链接支持。你能够在ConnectionString中指定不一样的参数值控制链接池的行为。好比下面的例子使OLE DB的链接池无效并自动地进行事务处理:

Provider=SQLOLEDB;OLE DB Services=-4;Data Source=localhost;Integrated Security=SSPI;

在SQL Server.NET Data Provider中提供了如下参数设置控制链接池的行为:Connection Lifttime、Connection Reset、Enlist、Max Pool Size、Min Pool Size和Pooling。

 

更多数据库链接信息,以及非ADO.net的链接字符串能够参看:

http://www.connectionstrings.com/

相关文章
相关标签/搜索