Sunteți pe pagina 1din 8

Beginners guide to accessing SQL Server through C#

Introduction
In this article I plan to demonstrate how to insert and read data from a SQL Server or MSDE database !his code should wor" on both SQL Server # I am using $%%%# and MSDE I am using &isual Studio $%%$# but this should wor" with &isual Studio $%%'# (eb Matri)# and the command line SD* !his code should wor" with both C# applications and C# web applications and webservices !his code does not compile on the +reeBSD with ,otor -./

Bac"ground
0art of m1 current pro2ect re3uired me too store and retrieve information from a database I decided to use C# as m1 target language since I am currentl1 reading Inside C# Second Edition -./ b1 !om 4rcher -./# which b1 the wa1 is a must have boo" 5owever I could not find an1 e)amples that were clear and 2ust generic accesing SQL Server with C#

6sing the code


I did not include a sample application because the code provide within the article can reall1 be dropped in and should wor" with no problem 4lso through out the article I will refer to SQL Server# MSDE is a free version of SQL Server that does not have some of the 76I tools and has a few other limits such as database si8e !his code will wor" on both without problem

Ma"ing the Love Connection


!here is no real voodoo magic to creating a connection to a SQL Server assuming it is properl1 setup# which I am not going to go into in this article# in fact 9E! has made wor"ing with SQL 3uite eas1 +irst step is add the SQL Client namespace:
using S1stem Data S3lClient;

!hen we create a S3lConnection and specif1ing the connection string

S3lConnection m1Connection < new S3lConnection=>user id<username;> ? >password<password;server<serverurl;> ? >!rusted@Connection<1es;> ? >database<database; > ? >connection timeout<'%>A;

S3lConnection ConnectionString

!he connection string is simpl1 a compilation of options and values to specif1 how and what to connect to 6pon investigating the &isual Studio 9E! help files I discovered that several fields had multiple names that wor"ed the same# li"e 0assword and 0wd wor" interchangeabl1 I have not included all of the options forS3lConnection ConnectionString at this time 4s I get a chance to test and use these other options I will include them in the article

User ID
!he 6ser ID is used when 1ou are using SQL 4uthentication In m1 e)perience this is ignored when using a !rusted@Connection# or (indows 4uthentication If the username is associated with a password 0assword or 0wd will be used

>user id<userid;>

Password or Pwd
!he password field is to be used with the 6ser ID# it 2ust wouldnBt ma"e sense to log in without a username# 2ust a password Both 0assword and 0wd are completel1 interchangeable

>0assword<validpassword;>-or>0wd<validpassword;>

Data Source or Server or Address or Addr or Network Address


6pon loo"ing in the MSD9 documentation I found that there are several wa1s to specif1 the networ" address !he documentation mentions no differences between them and the1 appear to be interchangeable !he address is an valid networ" address# for brevit1 I am onl1 using the localhost address in the e)amples

>Data Source<localhost;> -or>Server<localhost;> -or>4ddress<localhost;>-or->4ddr<localhost;> -or->9etwor" 4ddress<localhost;>

Integrated Sercurity or Trusted_Connection


Integrated Securit1 and !rusted@Connection are used to specif1 wheter the connnection is secure# such as (indows 4uthentication or SS0I !he recogni8ed values are true# false# and sspi 4ccording to the MSD9 documentation sspi is e3uivalent to true Note: I do not "now how SS0I wor"s# or affects the connection

Connect Timeout or Connection Timeout


!hese specif1 the time# in seconds# to wait for the server to respond before generating an error !he default value is CD=secondsA

>Connect !imeout<C%;>-or>Connection !imeout<C%;>

Initial Catalog or Data ase


Initial Catalog and Database are simpl1 two wa1s of selecting the database associated with the connection >Inital Catalog<main;> -or>Database<main;>

Network !i rary or Net


!he 9etwor" Librar1 option is essential if 1our are communicating with the server on a protocl other than !C0EI0 !he default value for 9etwor" Librar1 is dbmssocn# or !C0EI0 !he following options are available: dbnmpntw =9amed 0ipesA# dbmsrpcn =MultiprotocolA# dbmsadsn =4pple !al"A# dbmsgnet =&I4A# dbmsipcn =Shared Memor1A# anddbmssp)n =I0FES0FA# and dbmssocn =!C0EI0A 4nd as before 9etwor" Librar1 and 9et can be user interchangabl1 Note: !he corresponding networ" protocol must be installed on the s1stem to which 1ou connect

S3lConnection Gpen=A
!his is the last part of getting connected and is simpl1 e)ecuted b1 the following =remember to ma"e sure 1our connection has a connection string firstA:
Collapse H Cop1 Code

tr1 I m1Connection Gpen=A; J catch=E)ception eA I Console (riteLine=e !oString=AA; J

S3lConnection Gpen=A is a void function and does not return an error but throws an e)ception so remember to put it in a tr1Ecatch brace rather than having the program e)plode in front of the user

Command thee
SQL commands are probabl1 the most difficult part of using an SQL database# but the 9E! framewor" has wrapped up ever1thing up nicel1 and ta"es most of the guess wor" out

S3lCommand
4n1 guesses on what S3lCommand is used forK If 1ou guessed for SQL commands then 1ou are right on 4nS3lCommand needs at least two things to operate 4 command string# and a connection +irst weBll loo" at the connection re3uirement !here are two wa1s to specif1 the connection# both are illustrated below:

S3lCommand m1Command < new S3lCommand=>Command String># m1ConnectionA; // - or m1Command Connection < m1Connection;

!he connection string can also be specified both wa1s using the S3lCommand Command!e)t propert1 9ow lets loo" at our first S3lCommand !o "eep it simple it will be a simple I9SE,! command
S3lCommand m1Command< new S3lCommand=>I9SE,! I9!G table =ColumnC# Column$A > ? >&alues =BstringB# CA># m1ConnectionA; // - or m1Command Command!e)t < >I9SE,! I9!G table =ColumnC# Column$A > ? >&alues =BstringB# CA>;

9ow we will ta"e a loo" at the values table is simpl1 the table within the database ColumnC and Column$ are merel1 the names of the columns (ithin the values section I demonstrated how to insert a string t1pe and an intt1pe value !he string value is placed in single 3uotes and as 1ou can see an integer is 2ust passed as is !he final step is to e)ecute the command with:
m1Command E)ecute9onQuer1=A;

S3lData,eader
Inserting data is good# but getting the data out is 2ust as important !hats when the S3lData,eader comes to the rescue 9ot onl1 do 1ou need a data reader but 1ou need a S3lCommand !he following code demonstrates how to set up and e)ecute a simple reader:
tr1 I S3lData,eader m1,eader < null; S3lCommand m1Command < new S3lCommand=>select L from table># m1ConnectionA; m1,eader < m1Command E)ecute,eader=A; while=m1,eader ,ead=AA I Console (riteLine=m1,eader->ColumnC>/ !oString=AA; Console (riteLine=m1,eader->Column$>/ !oString=AA; J J catch =E)ception eA I Console (riteLine=e !oString=AA; J

4s 1ou can see the S3lData,eader does not access the database# it merel1 holds the data and provides an eas1 interface to use the data !he S3lCommand is fairl1 simple# table is the table 1our are going to read from ColumnC andColumn$ are 2ust the columns as in the table Since there is a ver1 high probabilit1 1our will be reading

more than one line a while loop is re3uired to retrieve all of the records 4nd li"e alwa1s 1ou want to tr1 it and catch it so 1ou donBt brea" it

S3l0arameter
!here is a small problem with using S3lCommand as I have demonstrated# it leaves a large securit1 hole +or e)ample# with the wa1 previousl1 demonstrated 1our command string would be constructed something li"e this if 1ou were to get input from a user:
Collapse H Cop1 Code

S3lCommand m1Command < new S3lCommand= >SELEC! L +,GM table (5E,E Column < > ? input !e)t# m1ConnectionA;

Its all fine and dand1 if the user puts in correct s1nta)# however# what happens if the user puts valueC# D,G0 table Best case scenario it will cause an e)ception =I havenBt chec"ed to see what this e)ample will do but it demonstrates a pointA# worst case 1ou can "iss 1our table goodb1e Mou could parse all user input and strip out an1thing that could cause problems G, 1ou could use an S3l0arameter 9ow the S3l0arameter class is prett1 big# but I will 2ust show 1ou a basic parameter usage Basicall1 1ou need three things to create a parameter 4 name# data t1pe# and si8e =note for some data t1pes 1ou will want to leave off the si8e# such as !e)tA
Collapse H Cop1 Code

S3l0arameter m10aram < new S3l0arameter=>N0aramC># S3lDb!1pe &arChar# CCA; m10aram &alue < >7arden 5ose>; S3l0arameter m10aram$ < new S3l0arameter=>N0aram$># S3lDb!1pe Int# OA; m10aram$ &alue < O$; S3l0arameter m10aram' < new S3l0arameter=>N0aram'># S3lDb!1pe !e)tA; m10aram &alue < >9ote that I am not specif1ing si8e > ? >If I did that it would trunicate the te)t >;

It is naming convention# it might be re3uired IBm not sure# to name all parameters starting with the N s1mbol 9ow how do 1ou use a parameterK (ill its prett1 eas1 as the following code shows
Collapse H Cop1 Code

S3lCommand m1Command < new S3lCommand= >SELEC! L +,GM table (5E,E Column < N0aram$># m1ConnectionA; m1Command 0arameters 4dd=m10aram$A;

9ow this "eeps a rogue user from highP2ac"ing 1our command string !his isnBt all there is to parameters if 1ou want to learn more advanced topics a good place to start is here-./

DonBt forget to close up when 1our doneQ

Closing a connection is 2ust as eas1 as opening it Rust callS3lConnection Close=A but remember to put it in tr1Ecatch because li"e S3lConnection Gpen=A it does not return errors but throws an e)ception instead
Collapse H Cop1 Code

tr1 I m1Connection Close=A; J catch=E)ception eA I Console (riteLine=e !oString=AA; J

(hen good connections go bad


!he trusted connection had alwa1s been a m1ster1 to me# I had never figured wh1 IIS and SQL server never seemed to get along +ortunatel1 0ete =moredipA pointed out a helpful section of the documentation !o ma"e it more simple I have decided to add it to this article I am going to split this into $ different sections IIS S# and other versions of IIS !o get started 1our going to want to ma"e sure os3l e)e is in 1our s1stem path# or find it It should be located wherever 1our SQL Server $%%% serverEclient tools director1 Gn m1 s1stem it is something li"e this: TInstall Director1TUV%U!oolsUBI99U +or simplicit1 I will use psuedoPvariables in the e)amples so as not to create confusion +or e)ample a psuedoPvariable will loo" li"e this: T&4,I4BLET !he server will be referred to asTSE,&E,TUTI9S!49CET If 1ou arenBt using an1 instance names it can be 2ust TSE,&E,T# =localA if the server is the local machine If 1ou are instance names it would be something li"e Server9ameUServerInstance etc etc I will also be using TD4!4B4SET to refer to the database name

IIS S on (indows $%%' Server


I "now this will wor" on IIS S with (indows $%%' Server because I have done it and that is currentl1 the onl1 GS with IIS S Gn IIS S the 4S0 9E! process runs under the account B9! 46!5G,I!MU9E!(G,* SE,&ICEB
Collapse H Cop1 Code

os3l PE PS TSE,&E,TUTI9S!49CET PQ >sp@grantlogin B9! 46!5G,I!MU9E!(G,* SE,&ICEB>

9ow our 4S0 9E! application will be able to log into the server 9ow all thats left is to grant access to the databases
Collapse H Cop1 Code

os3l PE PS TSE,&E,TUTI9S!49CET Pd TD4!4B4SET PQ >sp@grantdbaccess B9! 46!5G,I!MU9E!(G,* SE,&ICEB> os3l PE PS TSE,&E,TUTI9S!49CET Pd TD4!4B4SET PQ >sp@addrolemember Bdb@ownerB# B9! 46!5G,I!MU9E!(G,* SE,&ICEB>

!hese $ lines will add access to one of the databases So if 1ou want to add access to another database 2ust change TD4!4B4SET and run both lines

IIS D C
!his should wor" on all other IIS D C =possibl1 other versionsA combinations !he onl1 difference between IIS D C and IIS S is the account the 4S0 9E! process runs under IIS D C runs under a TM4C5I9E94METU4S09E! whereTM4C5I9E94MET is the machine name
Collapse H Cop1 Code

os3l PE PS TSE,&E,TUTI9S!49CET PQ >sp@grantlogin BTM4C5I9E94METU4S09E!B>

9ow our 4S0 9E! application will be able to log into the server 9ow all thats left is to grant access to the databases
Collapse H Cop1 Code

os3l PE PS TSE,&E,TUTI9S!49CET Pd TD4!4B4SET PQ >sp@grantdbaccess BTM4C5I9E94METU4S09E!B> os3l PE PS TSE,&E,TUTI9S!49CET Pd TD4!4B4SET PQ >sp@addrolemember Bdb@ownerB# BTM4C5I9E94METU4S09E!B>

!hese $ lines will add access to one of the databases So if 1ou want to add access to another database 2ust change TD4!4B4SET and run both lines

Loose Ends
Mou now have the basics re3uired to start using a SQL database in either webapplications or des"top applications !his article is b1 no means finished I plan to e)pand the article and add a sample application as time allows (ith information on stored procedures as well as an e)panded connection options section If 1ou have an1 suggestions please leave them in the forum below

Creating new database using Microsoft SQL Server (Express) Database file

Select windows authentication:

S-ar putea să vă placă și