|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionIn 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 [^]. BackgroundPart 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 codeI 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 will work on both without problem. Making the Love ConnectionThere 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 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.ConnectionStringThe 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 User IDThe
Password or PwdThe password field is to be used with the User ID, it just wouldn't make sense to log in without a username, just a password. Both
Data Source or Server or Address or Addr or Network AddressUpon 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
Integrated Sercurity or Trusted_Connection
Connect Timeout or Connection TimeoutThese specify the time, in seconds, to wait for the server to respond before generating an error. The default value is
Initial Catalog or Database
Network Library or NetThe Network Library option is essential if your are communicating with the server on a protocl other than TCP/IP. The default value for SqlConnection.Open()This is the last part of getting connected and is simply executed by the following (remember to make sure your connection has a connection string first): try
{
myConnection.Open();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
Command theeSQL 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. SqlCommandAny guesses on what SqlCommand myCommand = new SqlCommand("Command String", myConnection);
// - or -
myCommand.Connection = myConnection;
The connection string can also be specified both ways using the 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 . myCommand.ExecuteNonQuery();
SqlDataReaderInserting data is good, but getting the data out is just as important. Thats when the 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 SqlParameterThere 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 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 SqlCommand myCommand = new SqlCommand(
"SELECT * FROM table WHERE Column = @Param2", myConnection);
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 call try
{
myConnection.Close();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
When good connections go badThe 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 it to this article. 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 IIS 6 on Windows 2003 ServerI know this will work on IIS 6 with Windows 2003 Server because I have done it and that is currently the only OS with IIS 6. On IIS 6 the ASP.NET process runs under the account ' 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 thats 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.1This 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 osql -E -S %SERVER%\%INSTANCE% -Q "sp_grantlogin '%MACHINENAME%\ASPNET'"
Now our ASP.NET application will be able to log into the server. Now all thats left is to grant access to the databases. osql -E -S %SERVER%\%INSTANCE% -d %DATABASE%
-Q "sp_grantdbaccess '%MACHINENAME%\ASPNET'"
osql -E -S %SERVER%\%INSTANCE% -d %DATABASE%
-Q "sp_addrolemember 'db_owner', '%MACHINENAME%\ASPNET'"
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. Loose EndsYou now have the basics required to start using a SQL database in either webapplications or desktop applications. History
|
||||||||||||||||||||||