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/

相關文章
相關標籤/搜索