Beginners Guide to Accessing SQL Server Through C #

xiaoxiao2021-03-06  80

Introduction

In this article I plan to demonstrate how to insert and read data from a SQL Server or MSDE database. This code should work on both SQL Server, I am using 2000, and MSDE. I am using Visual Studio 2002, but this should work with Visual Studio 2003, Web Matrix, and The Command Line SDK. This Code Should Work With Both C # Applications and C # Web Applications and WebServices. This Code Does Not Compile on The FreeBSD with rotor [^].

BACKGROUND

Part of my current project required me too store and retrieve information from a database. I decided to use C # as my target language since I am currently reading Inside C # Second Edition [^] by Tom Archer [^], which by the way is a Must Have Book. However I Could Not Find Any Examples That Were Clear and Just Generic Accesing SQL Server with C #.

USING THE CODE

I did not include a sample application because the code provide within the article can really be dropped in and should work with no problem. Also 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 GUI Tools and Has A Few Other Limits Such As Database Size. This Code Work On Both WITHWITHWITHOUT Problem.

MAKING THE Love Connection

There is no real voodoo magic to creating a connection to a SQL Server assuming it is properly setup, which I am not going to go into in this article, in fact .NET has made working with SQL quite easy. First step is add the SQL Client Namespace:

Using system.data.sqlclient;

THEN WE CREATE A SQLCONNECTION AND SPECIFYING The Connection String.

SqlConnection MyConnection = New SqlConnection ("User ID = UserName;"

"Password = password; server = serverurl;"

"Trusted_Connection = YES;" "Database = Database;"

"Connection Timeout = 30");

Note: Line Break in Connection String is for Formatting Purposes ONLY

SqlConnection.connectionstring

The connection string is simply a compilation of options and values ​​to specify how and what to connect to. Upon investigating the Visual Studio .NET help files I discovered that several fields had multiple names that worked the same, like Password and Pwd work interchangeably. I .............................

User ID

The User ID is used when you are using SQL Authentication. In my experience this is ignored when using a Trusted_Connection, or Windows Authentication. If the username is associated with a password Password or Pwd will be used.

"User ID = userid;"

Password or PWD

The Password Field Is To BE Used with the User ID, IT Just Wouldn't Make Sense To Log in Withname, Just A Password. Both Password and PWD Arely Completely InterchangeAble.

"Password = validpassword;" - OR- "pwd = validpassword;"

Data Source Or Server or Address OR ADDR or NetWork Address

Upon looking in the MSDN documentation I found that there are several ways to specify the network address. The documentation mentions no differences between them and they appear to be interchangeable. The address is an valid network address, for brevity I am only using the localhost address In The Examples.

"Data Source = localhost;" - "server = localhost;" - "address = localhost;" - "-" adr = localhost; "" - or- "network address = localhost;" Integrated Sercurity or trusted_connection

Integrated Security and Trusted_Connection are used to specify wheter the connnection is secure, such as Windows Authentication or SSPI The recognized values ​​are true, false, and sspi According to the MSDN documentation sspi is equivalent to true Note:... I do not know how SSPI Works, OR affects the connection.

Connect Timeout or Connection Timeout

THESE SPECIFY THE, IN Seconds, To Wait for the Server to Respond Before Generating An Error. The Default Value IS 15 (Seconds).

"Connect Timeout = 10;" - OR- "Connection Timeout = 10;"

Initial Catalog or Database

Initial Catalog and Database Are Simply Two Ways of Selecting The Database Associated with The Connection.

"Inital catalog = main;" - OR- "Database = main;"

NetWork Library or Net

The Network Library option is essential if your are communicating with the server on a protocl other than TCP / IP The default value for Network Library is dbmssocn, or TCP / IP The following options are available:.. Dbnmpntw (Named Pipes), dbmsrpcn ( Multiprotocol), dbmsadsn (Apple Talk), dbmsgnet (VIA), dbmsipcn (Shared Memory), and dbmsspxn (IPX / SPX), and dbmssocn (TCP / IP) and as before Network Library and Net can be user interchangably Note..: The Corresponding NetWork Protocol Must Be Installed on The System To Which You Connect.

SqlConnection.Open ()

This is the last part of getting connecture and is simply executed by the fol loading (Remember to make your company "):

Try

{

MyConnection.open ();

Catch (Exception E)

{

Console.writeline (E.TOString ());

}

.

Command thee

SQL Commands Are Probably the Most Difficult Part of Using An Sql Database, But The .NET Framework Has Wrapped Up Everything Up Nicely and Takes Most of The Guess Work Out.

SQLCommand

Any guesses on what SqlCommand is used for? If you guessed for SQL commands then you are right on. An SqlCommand needs at least two things to operate. A command string, and a connection. First we'll look at the connection requirement. There Are Two Ways to Specify The Connection, Both Are Illustrate Below:

Sqlcommand mycommand = new sqlcommand ("command string", myconnection;

// - or -

MyCommand.connection = myconnection;

The Connection String Can Also Be Specified Both Ways Using The SqlCommand.comMandtext Property. Now Lets Look At Our First SqlCommand. To Keep IT Simple IT Will Be a Simple Insert Command.

Sqlcommand mycommand = new sqlcommand ("INSERT INTO TABLE (Column1, Column2)"

VALUES ('String', 1) ", MyConnection;

// - or -

Mycommand.commandtext = "INSERT INTO TABLE (Column1, Column2)" "VALUES ('String', 1)"

Now we will take a look at the values. Table is simply the table within the database. Column1 and Column2 are merely the names of the columns. Within the values ​​section I demonstrated how to insert a string type and an int type value. The string Value is placed in single quotes and as you can see. The final step is to execute the command with: mycommand.executenon query ()

SqlDataReader

Inserting data is good, but getting the data out is just as important. Thats when the SqlDataReader comes to the rescue. Not only do you need a data reader but you need a SqlCommand. The following code demonstrates how to set up and execute a simple Reader:

Try

{

SqlDataReader MyReader = NULL;

Sqlcommand mycommand = new sqlcommand ("Select * from table",

MyConnection);

MyReader = myCommand.executeReader ();

While (MyReader.Read ())

{

Console.writeline (MyReader ["Column1"]. TOSTRING ());

Console.writeline (MyReader ["Column2"]. TOSTRING ());

}

}

Catch (Exception E)

{

Console.writeline (E.TOString ());

}

As you can see the SqlDataReader does not access the database, it merely holds the data and provides an easy interface to use the data. The SqlCommand is fairly simple, table is the table your are going to read from. Column1 and Column2 are just the columns as in the table. Since there is a very high probability your will be reading more than one line a while loop is required to retrieve all of the records. and like always you want to try it and catch it so you do not break IT.

Sqlparameter

There is a small problem with using SqlCommand as I have demonstrated, it leaves a large security hole For example, with the way previously demonstrated your command string would be constructed something like this if you were to get input from a user:. SqlCommand myCommand = New SQLCommand

"Select * from table where column =" input.text, myconnection);

Its all fine and dandy if the user puts in correct syntax, however, what happens if the user puts value1, DROP table. Best case scenario it will cause an exception (I have not checked to see what this example will do but it demonstrates a point), worst case you can kiss your table goodbye. you could parse all user input and strip out anything that could cause problems OR you could use an SqlParameter. Now the SqlParameter class is pretty big, but I will just show you a basic Parameter Usage. Basical You NEED Three Things to create a parameter. a name, data type, and size. (Note for Some Data Types You Will Want To Leave Off The size, Such as text).

Sqlparameter myparam = new sqlparameter ("@ param1", sqldbtype.varchar, 11);

myparam.value = "garden hose";

Sqlparameter myparam2 = new sqlparameter ("@ param2", sqldbtype.int, 4);

myparam2.value = 42;

Sqlparameter myparam3 = new sqlparameter ("@ param3", sqldbtype.text);

myparam.value = "Note That I am Not Specifying Size."

"IF I DID That It Would Trunicate The Text."

IT IS Naming Convention, IT Might Be Required I'm Not Sure, To Name All Parameters Starting with The @ Symbol. Now How Do You Use A Parameter? Will ITS Pretty Easy As The Following Code Shows.

Sqlcommand mycommand = new sqlcommand ("Select * from table where color";

Mycommand.Parameters.Add (myparam2);

Now this Keeps a Rogue User from high-jacking your command string. This isn't all there is to parameters if you want to learn more advanced Topics a good place to start is here [^].

Don't forget to close up when your done!

Closing a connection is just as easy as opening it. Just callSqlConnection.Close () but remember to put it in try / catch because like SqlConnection.Open () it does not return errors but throws an exception instead.

Try

{

MyConnection.Close ();

}

Catch (Exception E)

{

Console.writeline (E.TOString ());

}

When Good Connections Go Bad

The trusted connection had always been a mystery to me, I had never figured why IIS and SQL server never seemed to get along. Fortunately Pete (moredip) pointed out a helpful section of the documentation. To make it more simple I have decided to add I am going to split this INTO 2 DIFFERENT Sections. IIS 6, AND Other Versions of Iis. To Get Started Your Going to Want To Make Sure Osql.exe Is in Your System Path, OR Find It Shove be located wherever your SQL Server 2000 server / client tools directory On my system it is something like this:.% Install Directory% / 80 / Tools / BINN / .For simplicity I will use psuedo-variables in the examples so as not to create Confusion. For example a psuedo-variable will look like this:% variable%. The Server Will Be Referred To As% Server% /% Instance%. If you are aren't using any iNstance Names it can be just% server%, Local) IF The Server Is The Local Machine. If you are all instance names it would Bething Like ServerName / ServerInstance ETC etc. I Will Also BE Using% Database% To Refer to the Database Name.iis 6 on Windows 2003 Server

I Know this Will Work ON IIS 6 with Windows 2003 Server Because I Have Done It and this is currently the Only OS with IIS 6. ON IIS 6 The ASP.NET Process Runs Under The Account 'NT Authority / Network Service'.

OSQL -E -S% Server% /% instance% -q "sp_grantlogin 'NT Authority / Network Service'"

NOW OUR ASP.NET Application Will Be Able To Log Into The Server. Now All That LEFT IS TO GRANT Access To The DataBases.

OSQL-E -S% Server% /% instance% -d% Database% -Q

"sp_grantdbaccess 'nt authority / network service'"

OSQL-E -S% Server% /% instance% -d% Database% -Q

"Sp_addrolemember 'db_owner', 'NT AUTHORITY / NETWORK SERVICE'" These 2 lines will add access to one of the databases. So if you want to add access to another database just change% DATABASE% and run both lines.

IIS 5.1

This should work on all other IIS 5.1 (possibly other versions) combinations. The only difference between IIS 5.1 and IIS 6 is the account the ASP.NET process runs under. IIS 5.1 runs under a% MACHINENAME% / ASPNET where% MACHINENAME% is The Machine Name.

OSQL -E -S% Server% /% instance% -q "sp_grantlogin '% machine machine% / aspnet'"

NOW OUR ASP.NET Application Will Be Able To Log Into The Server. Now All That LEFT IS TO GRANT Access To The DataBases.

OSQL -E -S% Server% /% instance% -d% Database%

-Q "sp_grantdbaccess '% machine machinename% / aspnet'"

OSQL -E -S% Server% /% instance% -d% Database%

-Q "sp_addrolemember 'db_owner', '% machinename% / aspnet'"

. ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

Loose Ends

You now have the basics required to start using a SQL database in either webapplications or desktop applications.This article is by no means finished. I plan to expand the article and add a sample application as time allows. With information on stored procedures as well as An Expanded Connection Options Section. If you have any suggestions please leave the in the forum below

History

20 August 2004: Added a section on SqlParameters 25 February 2004: Added information on setting up permissions with IIS 2 July 2003: Revised connection string section 28 June 2003: Fixed a few typographical errors 27 June 2003: Initial Release

转载请注明原文地址:https://www.9cbs.com/read-122861.html

New Post(0)