Documente Academic
Documente Profesional
Documente Cultură
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#
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;>
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
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-./
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
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
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