c#连接数据库代码集合Word格式.docx
《c#连接数据库代码集合Word格式.docx》由会员分享,可在线阅读,更多相关《c#连接数据库代码集合Word格式.docx(21页珍藏版)》请在冰点文库上搜索。
![c#连接数据库代码集合Word格式.docx](https://file1.bingdoc.com/fileroot1/2023-5/9/ef1f8971-39b2-412e-9b08-1b7efd0c554e/ef1f8971-39b2-412e-9b08-1b7efd0c554e1.gif)
InitialCatalog=pubs;
UserId=sa;
Password=asdasd;
trustedConnection:
IntegratedSecurity=SSPI;
(useserverName\instanceNameasDataSourcetouseanspecifikSQLServerinstance,onlySQLServer2000)
oConn.Provider="
sqloledb"
connectviaanIPaddress:
DataSource=190.190.200.100,1433;
NetworkLibrary=DBMSSOCN;
UserID=sa;
(dbmssocn=tcp/ipinsteadofNamedPipes,attheendoftheDataSourceistheporttouse(1433isthedefault))
SqlConnection(.NET)
-or-
Trusted_Connection=False"
(boothconnectionstringsproducesthesameresult)
Trusted_Connection=True;
declaretheSqlConnection:
C#:
usingSystem.Data.SqlClient;
SqlConnectionoSQLConn=newSqlConnection();
oSQLConn.ConnectionString="
myconnectionstring"
;
oSQLConn.Open();
VB.NET:
ImportsSystem.Data.SqlClient
DimoSQLConnAsSqlConnection=NewSqlConnection()
oSQLConn.Open()
DataShape
msDataShape
Provider=MSDataShape;
DataProvider=SQLOLEDB;
wanttolearndatashaping?
Checkout4GuyfFromRolla'
sgreatarticleaboutDataShaping>
>
Readmore
Howtodefinewhichnetworkprotocoltouse
Example:
NameNetworklibrary
dbnmpntwWin32NamedPipes
dbmssocnWin32WinsockTCP/IP
dbmsspxnWin32SPX/IPX
dbmsvinnWin32BanyanVines
dbmsrpcnWin32Multi-Protocol(WindowsRPC)
importantnote!
WhenconnectingthroughtheSQLOLEDBproviderusethesyntaxNetworkLibrary=dbmssocn
andwhenconnectingthroughMSDASQLproviderusethesyntaxNetwork=dbmssocn
AllSqlConnectionconnectionstringproperties
ThistableshowsallconnectionstringpropertiesfortheADO.NETSqlConnectionobject.MostofthepropertiesarealsousedinADO.Allpropertiesanddescriptionsisfrommsdn.
NameDefaultDescription
ApplicationName
Thenameoftheapplication,or'
.NetSqlClientDataProvider'
ifnoapplicationnameisprovided.
AttachDBFilename
-or-
extendedproperties
InitialFileName
Thenameoftheprimaryfile,includingthefullpathname,ofanattachabledatabase.Thedatabasenamemustbespecifiedwiththekeyword'
database'
.
ConnectTimeout
ConnectionTimeout15Thelengthoftime(inseconds)towaitforaconnectiontotheserverbeforeterminatingtheattemptandgeneratinganerror.
ConnectionLifetime0Whenaconnectionisreturnedtothepool,itscreationtimeiscomparedwiththecurrenttime,andtheconnectionisdestroyedifthattimespan(inseconds)exceedsthevaluespecifiedbyconnectionlifetime.Usefulinclusteredconfigurationstoforceloadbalancingbetweenarunningserverandaserverjustbroughton-line.
ConnectionReset'
true'
Determineswhetherthedatabaseconnectionisresetwhenbeingremovedfromthepool.Settingto'
false'
avoidsmakinganadditionalserverround-tripwhenobtainingaconnection,buttheprogrammermustbeawarethattheconnectionstateisnotbeingreset.
CurrentLanguage
TheSQLServerLanguagerecordname.
DataSource
Server
Address
Addr
NetworkAddress
ThenameornetworkaddressoftheinstanceofSQLServertowhichtoconnect.
Enlist'
Whentrue,thepoolerautomaticallyenliststheconnectioninthecreationthread'
scurrenttransactioncontext.
InitialCatalog
Database
Thenameofthedatabase.
IntegratedSecurity
Trusted_Connection'
Whethertheconnectionistobeasecureconnectionornot.Recognizedvaluesare'
'
and'
sspi'
whichisequivalentto'
MaxPoolSize100Themaximumnumberofconnectionsallowedinthepool.
MinPoolSize0Theminimumnumberofconnectionsallowedinthepool.
NetworkLibrary
Net'
dbmssocn'
ThenetworklibraryusedtoestablishaconnectiontoaninstanceofSQLServer.Supportedvaluesincludedbnmpntw(NamedPipes),dbmsrpcn(Multiprotocol),dbmsadsn(AppleTalk),dbmsgnet(VIA),dbmsipcn(SharedMemory)anddbmsspxn(IPX/SPX),anddbmssocn(TCP/IP).
ThecorrespondingnetworkDLLmustbeinstalledonthesystemtowhichyouconnect.Ifyoudonotspecifyanetworkandyouusealocalserver(forexample,"
."
or"
(local)"
),sharedmemoryisused.
PacketSize8192SizeinbytesofthenetworkpacketsusedtocommunicatewithaninstanceofSQLServer.
Password
Pwd
ThepasswordfortheSQLServeraccountloggingon.
PersistSecurityInfo'
Whensetto'
security-sensitiveinformation,suchasthepassword,isnotreturnedaspartoftheconnectioniftheconnectionisopenorhaseverbeeninanopenstate.Resettingtheconnectionstringresetsallconnectionstringvaluesincludingthepassword.
Pooling'
Whentrue,theSQLConnectionobjectisdrawnfromtheappropriatepool,orifnecessary,iscreatedandaddedtotheappropriatepool.
UserID
TheSQLServerloginaccount.
WorkstationIDthelocalcomputernameThenameoftheworkstationconnectingtoSQLServer.
note
Use;
toseparateeachproperty.
Ifanameoccursmorethanonce,thevaluefromthelastoneintheconnectionstringwillbeused.
Ifyouarebuildingyourconnectionstringinyourappusingvaluesfromuserinputfields,makesuretheusercan'
tchangetheconnectionstringbyinsertinganadditionalpropertywithanothervaluewithintheuservalue.
Access
Driver={MicrosoftAccessDriver(*.mdb)};
Dbq=C:
\mydatabase.mdb;
Uid=Admin;
Pwd=;
workgroup:
SystemDB=C:
\mydatabase.mdw;
exclusive:
Exclusive=1;
Uid=admin;
Pwd="
standardsecurity:
Provider=Microsoft.Jet.OLEDB.4.0;
DataSource=\somepath\mydb.mdb;
UserId=admin;
Password=;
workgroup(systemdatabase):
JetOLEDB:
SystemDatabase=system.mdw;
withpassword:
DatabasePassword=MyDbPassword;
Oracle
newversion:
Driver={MicrosoftODBCforOracle};
Server=OracleServer.world;
Uid=Username;
oldversion:
Driver={MicrosoftODBCDriverforOracle};
ConnectString=OracleServer.world;
Uid=myUsername;
Pwd=myPassword;
Provider=msdaora;
DataSource=MyOracleDB;
UserId=UserName;
thisone'
sfromMicrosoft,thefollowingarefromOracle
Provider=OraOLEDB.Oracle;
UserId=Username;
OSAuthent=1;
OracleConnection(.NET)
standard:
IntegratedSecurity=yes;
thisoneworksonlywithOracle8irelease3orlater
specifyingusernameandpassword:
UserId=username;
Password=passwd;
IntegratedSecurity=no;
declaretheOracleConnection:
usingSystem.Data.OracleClient;
OracleConnectionoOracleConn=newOracleConnection();
oOracleConn.ConnectionString="
oOracleConn.Open();
ImportsSystem.Data.OracleClient
DimoOracleConnAsOracleConnection=NewOracleConnection()
oOracleConn.Open()
missingtheSystem.Data.OracleClientnamespace?
Download.NETManagedProviderforOracle»
greatarticle!
"
FeaturesofOracleDataProviderfor.NET"
byRamaMohanG.atC#Corner
CoreLabsOraDirect(.NET)
UserID=scott;
Password=tiger;
Host=ora;
Pooling=true;
MinPoolSize=0;
MaxPoolSize=100;
ConnectionLifetime=0"
ReadmoreatCoreLabandtheproductpage.
msDataShape:
Provider=MSDataShape.1;
PersistSecurityInfo=False;
DataProvider=MSDAORA;
DataSource=orac;
userid=username;
password=mypw"
MySQL
odbc2.50Localdatabase:
Driver={mySQL};
Server=localhost;
Option=16834;
Database=mydatabase;
odbc2.50Remotedatabase:
Server=;
Port=3306;
Option=131072;
Stmt=;
Database