You are on page 1of 10

Lesson:08 Obtaining Data from a SQL 2005 Express Edition Database In this video we will briefly talk about

databases, specifically how to work with SQL2005 Express Edition databases. But before we run, we need to walk. So we will start off by talking about databases: what they are, why you use them, and how they are structured. And then we will demonstrate how to create and use the SQL2005 Express Edition database from within Visual C sharp, and finally I will demonstrate how to modify data that is stored in a SQLdatabase. So lets start small. What is a database? Well simply put, it is a structured repository for data. You save information in a database you, read the information from the database, you update the information, and sometimes you need to delete the information. The information is organized so it can be retrieved easily, can be sorted, can be grouped, can be related to other data, and thereby can be used to analyze information in a countless number of ways. So lets say you have a business and you want to keep track of your customers. You could store customer names in simple text files using notepad. But the problem is that after a while, there are so many names that it becomes unmanageable, and you have to scroll through this long file to find the name of the customer that you need to follow up with. So you decide to store the names of the customers in an Excel spreadsheet instead, which works for a while, but what happens when you want to view all the purchases in the month of April for your top ten customers? Well I suppose that it is possible in Excel, but it is not as easy as using a Relational Database Management System or RDBMS like SQLServer. And this is just the tip of the iceberg in terms of benefits in using the real database over a text file or an Excel spreadsheet. It is probably the most easy way to understand it though. Now up to now, SQLwas considered a high-end database server used in large companies to enable the management and the retrieval of relational database data. In SQL2005 Express Edition, however, you can harness the power in the most simple applications that you can dream up. [Start: 00:00:00 & End: 00:02:05] Now, were using the term RDBMS or Relational Database Management System. This is actually a philosophy or an approach to designing a database that is analogous in some ways to writing object-oriented code, although it is very different, different techniques, different goal, etc. But in Relational Database theory, you organize your data into table that are related with other tables and so on. So you might dedicate a table for customer names, and another

table for order information. Now, you could just create one table that contains both customer and order information. But then you run the possibility of having redundant information when you have a customer that orders twice. And then there is also the issue of data integrity. What if the customer called himself Bob on the first order and Robert on the second order? Or a better example might be if the customer moved. It would be difficult to determine that both orders were, in fact, from the same customer. So it makes sense to manage this information in separate tables. Now, there are really a lot of rules that were created back in the 1970s and the 1980s by the creator of Relational Database theory, and those rules are called normalization. And were not going to take the time to go over the rules, but be aware that Ive really just skimmed over this idea, and you can find out a lot more on your own. In most cases, you can normalize the database with just a little common sense. Once you see it done a few times, it is going to make a lot more sense to you. You will pretty much have the idea on it. So lets dig deeper into database objects. First of all, please take the time to read the document that I have supplied that accompanies these videos, because it is going to have some additional information that will supplement what I say here. So were going to start with the concept of a table. And a table is the foundational database object. A table consists of columns and rows, or rather records. [Start: 00:02:05 & End: 00:04:01] A single column in a single row is often referred to as a field of data. The columns define the type of data that will be stored in the table, and the rows or records are the actual data. So we might have a simple customer table with the following columns: first name, last name, address, state, ZIP, credit limit, customer since, and so on. We have probably left out a number of fields that should belong in there as well. But, I think you get the idea. In order to maintain data integrity, we need to define more information about each column, such as the type of data that is going to be stored in that column, and in some cases, like for example, string data, were going to have to define the maximum number of characters in the string. Well also need to define if a particular record can be saved, if it contains fields of information with null data.

Now, what is data integrity? It actually takes several forms, and it is one of the major things that a Relational Database System will help you maintain. For example, we may not want to allow somebody to add data to our database that sets our credit limit field to two thousand dollars, all spelled out T W O T H O U S A N D and so on. What we want is a numeric number that represents currency. So we probably use a currency data type, and that will exclude the possibility that somebody will spell out two thousand dollars, because we cannot add the words two thousand dollars to a currency value of 1500 or so on. Now, the same is true for the customer since field. We can see that we have defined that as a date data type, and so it should only allow date values and state, for example. It should only allow two characters, for example, TX for Texas, CA for California, and so on. [Start: 00:04:01 & End: 00:06:01] Now, moving on, we may want to allow a record to be saved to the database if that record does not include an address. But, we may not want to allow a record that does not have a name or the first name and the last name is missing, for example. That will not make a whole lot of sense. So what we could do is define certain fields like address, state, and ZIP to be nullable fields. These fields do not have to be supplied in order for the record of data to be saved successfully into the database. However, if first name or last name is missing, the database can reject the attempt by the application or the user or whatever the case might be, to try and save data into the database. This is in an effort again to maintain the integrity of the data in the database. Data integrity is, simply put, just an attempt to make sure that the data that is in the database, is correct and meaningful and useful for the purpose of any applications that might use the data. Now finally, were going to want to add one more column, and were going to use this column to uniquely identify this row of data. Were going to call the column customer ID. And this type of column is referred to as a key, or better yet, a primary key. Now, why do we need a key? A key is a way to differentiate two customers, or rather two records that have the same name, for example. Now while you may have two records with the exact same information, has the same name, same address, and so on, one field of data should be used to differentiate the rows, and typically you are going to want to use a numeric field for this information. And so we can set a special property of that column called identity, which will automatically number each record of data as it is added to the database. [Start: 00:06:01 & End: 00:08:06]

And we will use that automatically-numbered field of information for each record of data as its primary key, as what differentiates it from the other records in the database. The primary key is also used in order to relate two tables together. Now in addition to our customer table, lets define an order table. So you can see here that I have defined four columns: order ID, order date, order amount, and payment type. Now again, I probably left out some important information. So for our purposes, were just wanting to investigate how this all works. But in a more real-life scenario, we may need to include some more information here. Most importantly, we left out the information that allows us to determine who actually created this order. Now, this is a real problem that were going to need to address now. We need to relate a row from this table back to a row in our customer table, and the way we do this is with a foreign key. So were going to add one more column of information called customer ID. And now, it just still happens that we name this field the same thing that we named it in the customer table, but we did not need to. We could have named it anything we wanted to name it. However, to make things easier to understand, we wanted to name them exactly the same. Now by creating an order record and including the customer ID, we can easily tie back any order to the customer that created the order. Also, we can easily tie back all of the order ever created by this customer, and tally how much the customer has spent with our company and a lot more. [Start: 00:08:06 & End: 00:09:55] So just to recap, we have a primary key in the customer table called customer ID, and we have another key, another field in the order table that we have called a foreign key in the order table, and so now it is possible to relate these two tables together, the primary key and the foreign key can be related together, thus making a relationship between these two tables. But from a database perspective, we still have a problem. If I were to delete a customer in the customer table, all of the associated orders that were placed by that customer would be what is called orphaned, which means that we will never be able to tell who ordered those items. That will be huge problem. So what we need to do is create a special object in the database called a constraint, specifically what is called a foreign key constraint between the order table and the customer table. And when we do this, nobody will be able to delete a customer before deleting all the associated orders first. The database just will not allow it because doing so would violate the integrity of the data in the database. You cannot have orphaned rows. So that was a pretty quick overview, and I hope you can see now at least some of concepts of what a relational database is. Relational databases help key data structured, and therefore

easily managed. It reduced redundant data by splitting up duplicate data into its own tables, and it helps to maintain the integrity of the data among other things. So lets now transfer this to databases into creating SQL2005 database. Then were going to add objects like tables and fields and relations to the database, and then finally, we will add some data to it. So I have taken the liberty of creating a new project called lesson 08, and I just want you to know that there are actually several different ways that you can go about creating a new SQLExpress 2005 database. But Im going to use a more project-base approach for this example. [Start: 00:09:55 & End: 00:12:04] So with my project open, Im going to right-click on my project, and select add new item. And from the install template section, Im going to select a SQLdatabase. And then Im going to change the name of the database to lesson08.mdf, and select add. Now by default, it is going pop open this data source configuration wizard. Lets not worry about this for right now. Im just going to select the cancel button, and then Im going to double-click this file within the solution explorer so that I can open up the database explorer with my database already loaded in. Now you can see here that there are some files underneath the lesson 08.mbf file that is loaded under the data connections node. What we want to concentrate on are tables, and by default, there are going to be no tables in the database. But what I want to do is right-click and select add new table. Lets reposition a things here so we can see the main area a little better. Now we have a designer surface where we can create a new table, and were going to be forward looking, and create two tables that will be eventually used within our RSS reader application. We will create them again in the future, but just so we can have something to talk about, were going to create a folder table, and then were going to create a channel table. Lets start with the folder table. So Im going to put my cursor in this little box next to column name, and Im going to create a folder ID, which Im going to use as my primary key for this table. For the data type, Im going to put my mouse cursor in the data type column, and then Im going to use the little combo box, and find the integer data type. [Start: 00:12:04 & End: 00:14:14]

And then Im going to deselect allow nulls. I do not want this field to allow any nulls. Now if you remember from discussion a few moments ago, whenever you are creating primary key, were going to set a special property of this column called the identity property, which will automatically number each row of data or each record of data that is added to this table. So to turn on that automatic numbering, what were going to need to do is scroll down in this column properties tab, and find the identity specification. And Im just going to double-click it. I need to open this up, right. It is the identity, were going to turn this to yes. Now there are some other things, identity increment and identity seed. Do not worry about those. Just leave them at their defaults for right now. And then,I want you to select in the next row where were defining columns, and were going to create a second column called folder name, and this time you can see that it defaults to nchar[10]. What we want to do is place textual information, and allow up to 50 characters, and allow it to be nullable. So were going to select this nvarchart[50]. Were going to turn off the null, allow null for right now. And that is about all we need to do with one exception. Right now, even though we have defined our primary key, we have not told the database that we intend for this column to be used for that purpose. So what we will do is select this little button on our toolbar to set the primary key. [Start: 00:14:14 & End: 00:16:00] And when I do, notice that there is a little key that is added right next to the folder ID column. Im going to select the save button on my toolbar, and it asked me to choose a name for my table. I do not want table 1 to be the name of this table. I want something a little more descriptive. Im going to call this table folder. Select the OK button, and now as you can see in the database explorer on the left-hand side, a new table has been created called folder, and I can even drill down to see all the columns that are related to this folder, folder ID and folder name. When I select either of these columns, notice over on the right-hand side in the property window, we can view properties about that column. Now, we cannot change it here. It is all grayed out. But we can still see some information about, for example, the folder ID, whether it is an identity or not, the length and so on. So we have created our first table. Lets now close this designer, and we will just close everything. We will go back to tables, and were going to create a second table. Add new table, and Im going to do this a little bit quicker this time since I walked you through it slowly last time. And this is going to be a table that will hold the channels. We will talk about this when we get to the RSS reader application. We want to make this an integer, and turn off nulls. And I also want to set it as

my primary key. Our channel will need a title. So Im going to go to nvarchar[50], and I want to change it from a length of 50, by default, to a length of lets say, 250. So that will allow me to put up to 250 characters of data, of string data in this column. Now, I also want to not allow it to accept any rows. I think I may have made a mistake in my channel. As I remember, I did not turn on the identity column. So Im going to go back, go to my is identity property, and select yes. Now, we will continue on. Channel will need a URL, and once again, Im going to use the nvarchar, but Im going to change it from 50 to a length of 250, and Im not going to allow it to be null. Or actually, in this case, I will go ahead and allow it to be null, and finally, Im going to need to create foreign key back to the folder table, because we want there to be a relationship between the folder table and our new channel table that were creating. Folder ID, in this case, we want an integer and were not going to allow it to accept nulls. I think I got it right. So when I select save, it is going to ask me for a name, and we will call this channel, and select OK. [Start: 00:16:00 & End: 00:19:04] So as you can see, I now have a second table here with four columns defined. And we can move on to the next bit of business, which is to create a relationship between these two tables. Now, there are actually several different ways that we can go by creating these relationships. There is a straightforward way and then there is a more visual way that we can do it. And Im going to take the more fun, visual approach for this first time. And to do that, Im going to create a database diagram. So over here in my database explorer, Im going to select database diagram. So Im going to right-click and select add new diagram. It is going to say that it does not have one or more of the database objects required to use database diagram. You should create them, select yes, and give it a moment or two. And then it is going to pop up and ask for the tables that you want to add to this diagram. We want both of these added. So Im going to select the add button once, and select it a second time, and then click the close button, and now what you can see is kind of a visual view of the table that I have selected, the two tables that are in my database. Now the way that you create a relationship between these two tables is really simple. All you have have to do is put your mouse cursor over the first one, kind of in this gray area, and hold down and drop it in its corresponding primary key in the other table. And when you do, it pops open some dialogue boxes. We could have used this dialogue-based approach to create it in the first place, but I thought it will be fun to create a database diagram, but either way, we have to go through the same steps at this point. So it is just that these are filled in automatically for us. The primary

key table on the left-hand side is folder, and the primary key itself is the folder ID, and then you can see over in the foreign key tables, the channel table and the foreign key column itself is the folder ID. That looks correct. [Start: 00:19:04 & End: 00:21:10] Notice that it gave it a default name of fk_channel_folder. That looks good so I wont change that, and select the OK button, and Im going to select OK a second time, and Im going to save this whole project and everything including the tables. And I need to give it a diagram name, diagram 0 is just fine. And after it asks us all these questions, we should be in good shape now. I have expanded the data connections one more time to get back. You can see I have now my diagram. I have my tables. And I know that I have a relationship between those two tables. So the next order of business is to start adding data to our table. Lets do this: Lets first of all start with our folder, and were going to right-click it. And were going to select show table data. And in the main area it will what looks like a grid. Notice at the very top we have columns, and what were going to do start typing in data for the rows. So folder name, were going to call this first folder, and then Im going to use my tab key on my keyboard, and notice that it automatically put 1 in the folder ID for my first record of my first row of data, and then use the tab key again because I do not want to mess with the folder ID. It is going to automatically number itself. So here I will put second folder, and notice as Im making a modification to a given record or a given row, that on the left-hand side I get this little pencil that looks like it is editing, and that is what we were doing. Were editing or making a modification to the row. And once again, here were going third folder, and so on. [Start: 00:21:10 & End: 00:23:16] So we have added three rows of data to our database. Now we can use these little navigation buttons here at the bottom. We can move to the first row, and notice the little arrow cursor goes to the first row of data. Notice that I can go to use these next buttons, and the next/previous buttons will let me go one at a time, or I can use this move to the last row of data, and I can also select to move to a new row. So it automatically places me at the position or I can add yet a fourth folder and so on. I can also just type in a number and hit the enter key on my keyboard, and it puts me to that row of data in my database. So I have made modifications to my data. If I want to change something, and just for example make a

small change to the folder name, all I have to do is go to that row, just type it in, and click somewhere off that row, or just use the tab key on my keyboard again, and that change has now been saved to the database. If I want to delete a row of data, all I need to do is select it here on the right-hand side, and then I can click the delete button on my keyboard, and it will say, You are about to delete one row. Do you want to permanently delete this? You wont be able to undo it. Select yes, and now we no longer have a folder ID of 3. You can see that it is gone. We have first, second and forth folder. So that is just generally how to navigate through a table of data, and create and change and delete the data in the table, so were in good shape. Lets go on to our channel. Were going to take the same steps. Show table data. Lets move some things around here so we can see everything. And were going to start adding some data here. First title. We can type anything here for now, first URL, and were going to need to give it a folder ID. Now, lets see if we can use the tab key on our keyboard, and what will happen. It says that No row was updated. The data in row 1 was not committed. The problem was that we cannot insert the value of null into the column folder ID. So what we need to do is use either folder ID 1, 2 or 4, because those are the only three folder IDs that we have in our folder table. So lets use folder ID No. 2, and hit the tab button again, and notice that this time were successful. [Start: 00:23:16 & End: 00:25:58] So what is the chance that we will be able to change this to a number that is not in our folder table? Like 7, we do not have a folder ID of 7 in our folder table. So when I hit the tab button on my keyboard, it says that the data in row 1 was not committed. This particular problem is that The update statement conflicted with a foreign key constraint FK channel folder. So basically, this again ensures data integrity. We cannot create a channel because there is no associated folder ID of 7. So we have to use only a folder ID that is associated. We can use the No. 4, and it is updated successfully. Now lets go ahead and do a couple more here. Second title, second URL, and a folder ID of 1, and third title, third URL and 2. So lets do this now, just for fun. Were going to go back to our folder table, and lets try to delete. Lets right-click it, and select show table data. Lets try to delete this fourth folder. So Im going to select the delete button on my keyboard, and it asks, you are about to delete one row. Click yes to permanently delete the row, you will not be able to do the

changes. So right now, it looks like it is going to let us, and then we get an error message that says, delete statement conflicted with the reference constraint, FK channel folder. [Start: 00:25:58 & End: 00:27:50] So you can see that in order to maintain data integrity, the database is not going to allow us to delete a row from the folder that would, in essence, create orphan tables, or orphan rows rather, in my channel table. At this point you might get tired hearing what Im about to say, but we have really just scratched the surface of working with tables, and columns, and records, and constraints with the SQL2005 Express Edition database. And you might be wondering, what are we going to do with this data? How does it really benefit us to put all this data in the database? In the next couple of videos, were going to look at how to enter and retrieve the data from and to the database using a Windows application. So were going to be able to represent the data in a grid or in textboxes, make changes, and save them back to the database. This is when it actually all starts coming together, and starts becoming a lot of fun. So just hang in there. Were almost to some things that will really allow you to create powerful applications. Were going to stop here for right now. If you enjoyed watching this video, please visit www.learnvisualstudio.net to download and watch over 500 videos just like this one aimed at all skill levels on many different topics related to C#, Visual Basic.NET, ASP.NET and more. Thank you. [Start: 00:27:50 & End: 00:02:05]

You might also like