You are on page 1of 12

ADO.Net makes connections to SQL databases very easy.

Visual Studio ships with SQL Express for development, but can only be used on the local machine. SQL Server and SQL Express are essentially the same.

In this short example we create the objects necessary to connect to a SQL database, query a table, retrieve the results and display them. You may have to change the database path depending on the location, and contents, of your SQL Express sample databases. Sample databases for SQL Express can be downloaded from the Microsoft Website.

We have used the "@" symbol to denote a verbatim string, a string that is taken as is. This allows for multi line strings and we do not have to escape characters such as backslash in filenames. It also means that the connection string is more readable when separated onto multiple lines.

Connected Mode
string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=""C:\SQL Server 2000 Sample Databases\NORTHWND.MDF"";Integrated Security=True;Connect Timeout=30;User Instance=True";

SqlConnection sqlCon = new SqlConnection(connectionString); sqlCon.Open();

string commandString = "SELECT * FROM Customers"; SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon); SqlDataReader dataReader = sqlCmd.ExecuteReader();

while (dataReader.Read()) { Console.WriteLine(String.Format("{0} {1}", dataReader["CompanyName"], dataReader["ContactName"])); } dataReader.Close(); sqlCon.Close();

As we have said previously, the SqlDataReader works in connected mode, so each call to SqlDataReader.Read will stream data from the server. It is also sequential, so once a record has been read, you can't access it again without executing the sqlCommand.ExecuteReader method again. The time between sqlCon.Open() and sqlCon.Close() there is a connection to the server. If you application opens the connection on start-up and doesn't close it until it exits you can cause unnecessary record or table locks. The way around this is by using a DataSet which will download a local copy of a subset of the main database that can be manipulated and changes sent back to the server later on.

Disconnected Mode

Disconnected mode will execute a query on the server and return the results in a DataSet object. This DataSet can then be used to display data, modify, insert or delete records without a database connection. When all changes have been made, the changes are sent back to the server.

string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=""C:\SQL Server 2000 Sample Databases\NORTHWND.MDF"";Integrated Security=True;Connect Timeout=30;User Instance=True";

string commandString = "SELECT * FROM Customers";

DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(commandString, connectionString);

da.Fill(ds,"Customers"); // Customers is the name of the DataTable

foreach (DataRow dr in ds.Tables[0].Rows) { Console.WriteLine(String.Format("{0} {1}", dr[1].ToString(), dr[2].ToString())); }

Database Explorer

You can also use the Database Explorer to add data elements to an application. To show the database explorer, click on the view menu and select Database Explorer or press Ctrl+Alt+S. You can add a reference to a database by creating a new connection. The process is described in more detail in the tutorial which covers Data and Windows Forms.

From the Database Explorer you can, in most cases, just drag and drop tables to a form to create a data bound grid view or control.

Updating in Connected Mode

The important thing to remember about connected mode is that updates are processed as a command is executed, whereas using Disconnected methods allow the data to be previewed and further amended before being committed to the server.

Additional SQL commands must be created after the first reader has been closed, or you will have to create new objects.

string connectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=""C:\SQL Server 2000 Sample Databases\NORTHWND.MDF"";Integrated Security=True;Connect Timeout=30;User Instance=True";

SqlConnection sqlCon = new SqlConnection(connectionString);

sqlCon.Open();

string commandString = "SELECT * FROM Customers"; SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon); SqlDataReader dataReader = sqlCmd.ExecuteReader();

while (dataReader.Read()) { Console.WriteLine(String.Format("{0} {1}", dataReader["CompanyName"], dataReader["ContactName"])); } dataReader.Close();

commandString = "UPDATE Customers SET ContactName = 'Jane Doe' WHERE CustomerID = 'ALFKI'"; sqlCmd = new SqlCommand(commandString,sqlCon); sqlCmd.ExecuteNonQuery();

sqlCon.Close();

Updating in Disconnected Mode

Disconnected updates are processed by manipulating the DataSet object. The Rows indexers access the record and the field.

ds.Tables[0].Rows[0][2] = "Jane Doe";

You will also need to specify and Update or Insert command to the data adaptor to instruct the server how it should update the table. Luckily there is a built in tool to help with this called the SqlCommandBuilder.

SqlCommandBuilder myBuilder = new SqlCommandBuilder(da); da.UpdateCommand = myBuilder.GetUpdateCommand();

Changes to the DataSet are not committed to the server until the Update method is called from the DataAdaptor.

da.Update(ds, "Customers");

In the next tutorial we will look at how to use data on Windows Forms applications.

Close down the project you have open, and click File > New Project to create a new one. To find the MDF database you created in the previous section, look in the Projects folder of Visual Studio 2010 (or whatever version you are using). Double click the name you gave to your project and you should see the MyWorkers.mdf file. (If you still can't find it, do a search using that file name.) Copy it somewhere like the root of C:\ if you're a XP user. This is so that you're not working with very long file paths. Once you have copied it over to your C drive, XP users would then only have a path like this: C:\\MyWorkers.mdf If you leave it where it is, the file path would be this: C:\\Documents and Settings\\pc_name\\My Documents\\Visual Studio 2005\\Projects\\cSharp\\dbtests\\MyWorkers.mdf Which is a bit long and unwieldy! For Vista and Windows 7 users, copy the database file to your Documents folder. The file path would then be: "C:\\Users\\Owner\\Documents\\MyWorkers.mdf" If you didn't create a SQL Server Express database then you can use ours. It is amongst the files you downloaded at the start of the course, in the databases folder. You will also find an Access version of the same database, just in case the SQL Server Express one doesn't work for you.

How to Connect to a SQL Server Express Database


To connect to a database using SQL Server Express, you first need to set up a SQL Connection object. You then need something called a connection string to tell C# where the database is. To set up a connection object, double click the blank form. Just outside of the Form Load event add the following: System.Data.SqlClient.SqlConnection con; Your coding window should look like this:

Inside of the Form Load event, add the following: con = new System.Data.SqlClient.SqlConnection(); When the form loads, a new SQL Connection object will be created with the name of con. Here's what your code should look like:

Now that we have a connection object, we can access the ConnectionString property. To see what the string should be, click the Data menu item at the top of the C# .NET software. Then select Show Data Sources. This will display a new tab where the Solution Explore is:

Click Add New Data Source and you'll see a Wizard appear. On the first screen, make sure Database is selected and then click the Next button get to the Choose your Data Connection step. Click the New Connection button, and you'll see the following:

The Data Source area has a Change button. Click this to see the following:

Select Microsoft SQL Server Database File (SqlClient). Then click OK.

Click the Browse button and browse to the location where you saved your database. The Add Connection box will then look something like this:

Click the Test Connection button to see if everything is working. Then click OK to get back to the Choose your Data Connection step. Expand the Connection String area, and the dialogue box should look like this:

Highlight the entire string (XP users):

And this for Vista or Windows7:

Now hold down the CTRL key on your keyboard. Press the letter C to copy the string. Go back to the Form Load event in your coding window and press CTRL then the letter V to paste the connection string. You'll have lots of red underlines, but don't worry about that. Cancel the wizard, because we're done with it - we only wanted the connection string! Just after the SqlConnection( ) line, type the following:

con.ConnectionString Type an equals sign then a double quote: con.ConnectionString = " Now move your connection string up to just after the quote mark: con.ConnectionString ="DataSource=.\SQLEXPRESS; AttachDbFilename =C:\MyWorkers.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"; At the end of that long connection string, type another double quote mark. End the line with the usual semicolon. Your coding window will then look something like ours below (we've got word wrap switched on):

Vista/ Windows 7:

Notice that we still have error underlines in the connection string. There are two of them in the XP code, and five for Vista/Windows 7, all after the backslash character. It is the backslash character that is the problem. This is considered a special character in C# programming, so it needs to be escaped. To escape a backslash character (or any other character) just type another backslash before it:

There are now four backslash characters in the code above, two before SQLEXPRESS, and two before MyWorkers.mdf. Add more backslash characters to your own code to get rid of the errors. All the code does, though, is to tell C# where the database is, and sets a few properties. You can add more database properties here, as well. For example, if the database required a user name, you'd add this: User ID=your_user_name; After your connection string, you can then try to open up a connection to the database. Again we use our con object: con.Open(); When the connection is open, we'll be writing code to get all the records. Once we've done that, we can close the connection: con.Close(); Add two message boxes to your code, and your coding window should look like ours:

Run your programme and test it out. You should see the "Database Open" message appear first, followed by the "Database closed" message. Then the form should load. Congratulations! All that hard work and you have now made a connection to your SQL Server Express database!

You might also like