Wednesday, July 27, 2005

ADO.NET Basics: Connecting to a DataBase

Ok, I have a big problem with ADO.NET. I don't seem to understand it very well. So in order to do so I am going to write little mini how-to's for ADO.NET. The first one is going to be connecting to a database. All my code will be in C#.

We are going to assume you have a SQL Server database and all commands will be against SQL Server. So be sure you impor the right namespace just so you can know it is:

using System.Data.SqlClient;

First we need to come up with the information that we are going to use to connect to the database. We are going to connect to the NorthWind database with User and the username and Password as the password.

So here is a generic connection string.

string ConnectionString = "server=myServer;uid=myUser;pwd=myPassword;database=DataBase"

Here is how we are going to customize it.

string ConnectionString = "server=myServer;uid=User;pwd=Password;database=NorthWind"

Next is constructing the connection.

SqlConnection Connection = new SqlConnection(ConnectionString);

You need to be sure that you take the string that you have the database information inside the parenthesis of the the SqlConnection command

Next is a very important step. Opening and closeing the connection.

Connection.Open();
Connection.Close();

See basically you take the name that you constructed it with and extend it use Open and Close.

So lets put all this together in one with a try catch block for error testing.

string ConnectionString = "server=myServer;uid=User;pwd=Password;database=NorthWind"

SqlConnection Connection = new SqlConnection(ConnectionString);

Try
{
Connection.Open();
Hello
Connection.Close();
}
catch()
{
}


If you run that with against your databse inside of your web application you should have a blank page that says Hello. If not you will probably be looking at an error of some sort. Just use that screen to debug. This should also work in a windows forms application.

0 Comments:

Post a Comment

<< Home