Вы находитесь на странице: 1из 15

SQL Server 2005 Compact Edition

Tutorial:

CRUD - (Create, Read, Update, and Delete)

Version: 9/24/2007

By: Chris Conley


cconley@c-solutions-inc.com
C Solutions, Inc
www.c-solutions-inc.com
O) (918) 307-0991

Copyright 2007
For single tier applications, I love SQL Server Compact Edition 2005. It gives you the
database accessibility of SQL, all while not needing access to a server install of SQL
Server. Over the years Microsoft has offered a number of other ways to work with data
in single tier applications, but none have been nearly as comparable, nor effective for me,
as SQL Server compact edition. XML files, and Access databases are just a couple of the
previous data access modes that were made available by Microsoft. Both of these had
their own limitations and frustrations. For XML files, querying them was a pain, speed
was slow, and it inherently has a lack of security. While Microsoft Access forced you to
load on the client computer the Microsoft Jet database. The Jet database system left a bit
to be desired in the security category as well.

SQL Server Compact Edition 2005 is a great leap forward for single tier database aware
applications. In case you didn’t know, single tier applications are ones where the
application interface and data are on the same computer.

Some of SQL Server Compact Edition‘s biggest features:


 The database files can be encrypted with RSA 128 bit file encryption
 Supports databases files up to 4GB
 Data can be accessed with a subset of T-SQL
 Support for transactions
 Can be run in a Windows, or in a Windows mobile application
 Supports data synchronization
 Database engine uses about 5 MB of memory and about 2 MB of disk space

One of the best things about it all is, it's free.

In order to run the examples shown below, you must first install SQL Server 2005
Compact Edition, as well as ‘Microsoft SQL Server 2005 Compact Edition Tools for
Visual Studio 2005 Service Pack 1’. Both of which can be found in a search from the
Internet.
Now to go over how you can actually use this in a Windows application.

First, to add a new SQL Server 2005 Compact Edition database, we select from the
’Data Sources’ tab, ‘Add New Data Source’.

Click this, then it will bring you to the ‘Data Source


Configuration Wizard’ dialog box. On this, hit the
‘Database’ option.

This will take you to the next


screen, which allows you to
choose your data connection.
Click the button that says “New
Connection”.
This will take you to the next screen, entitled
‘Add Connection’. Change the data source
from the default of SQL Server to SQL
Server Compact Edition. To do so, hit the
‘Change’ button to bring up this screen,
‘Change Data Source’. After you hit the ‘OK’
button, it will bring up the following screen,

also called ‘Add Connection’.


Add Connection Screen
On this screen, the first thing you need to do is add the location of your database. To do
so, hit the ‘Create’ button. This will take you to
the next screen, where you can create a new SQL
Server 2005 Compact Edition Database file. As
you can see below, I've called mine
‘SSCE_CRUD’. FYI. All SQL Server 2005
Compact Edition Database files are given in an
extension of ‘.sdf’. As you can see, you have the
chance to do a couple other things on this dialog
box as well: encrypt the database by selecting the
similarly named checkbox, and setting a
password by simply entering in the new
password and then filling in the confirmation
textbox below. Remember, encrypting the
database and setting a password are optional. Of
course depending upon your application’s needs,
you may or may not want to do this. Also,
Microsoft warns the encryption level they use on
this file is not set for the highest level of security, so, they say it is very safe compared to
a non-encrypted database, but far from being unbreakable security for the database’s data
file.

For the purposes of simplicity for this tutorial, I gave a password of ‘password’. As you
can see from the screen below, the system really does not like this password and requests
one of a much higher complexity level. It does give you the option of allowing you to
use whatever password you want, though, even if it does not meet it’s recommended
minimum
‘complexity
requirement’ it
gives you.
So, I selected yes to continue with this password.

Our ‘Add Connection’ screen


now looks like this:

If you want to be paranoid, you


can hit the Test Connection’
button which should show you
that the test connection
succeeded. Now simply hit the
‘OK’ button.

Now you can see our new


database file in the
updated Data Source
Configuration Wizard
dialog box:
Now it's wanting to
know if you would like
the application to keep
sensitive connection
string information, or
exclude it. I always select
no, exclude sensitive data
from the connection
string. I prefer setting this
in application code. After
you've selected yes or no,
from the radio button list,
hit the next button on the bottom of the dialog box to continue. After having done this, I
was greeted with the dialogue seen below:
I tell its yes with the yes button.

Then it gives me the next dialog box:

I tell it no I want to use the existing file, by hitting the ‘No’ button.

Then the next screen, by default, has the ‘Yes’ checkbox selected. I preferred to uncheck
it so it looks like the screenshot below. This is because I do not want to save the
connection string in the application's configuration file. If you like, you can leave the yes
checked. Then hit the ‘Next’ button.
This takes you to the screen below, which, I simply hit ‘Finish’ because I do not want to
add any database objects at this time.

Now that we've got our database created we can get down to doing some work on our
Windows form. I have changed our default form’s text property to ‘Days Of The Week’.
I have added a label, whose
text property is set to
‘Weekday’. And I have added
a button, whose text property is
set to ‘Insert’, and name set to
‘btnInsert’. I like to add on all
of the components I use, which
I'm going to do any kind of
programming against, the first
two or three letters, or more
sometimes, of the name
property I give to it to be
descriptive of what the
component is. So I can look at
it in code, say, in a printout,
then I can intuitively know
what the component type is without having to look at the Design view screen. I have
also added a text box to the screen, whose name property is ‘txtWeekday’. The ‘txt’ in
the name property is for the same reasons as outlined in the sentences above.
Also, if you look in the Solution Explorer
under references, you will find a reference is
already setup for you for SQL Server
Compact Edition 2005.
The application, however, does not know where you will be using SQL Server Compact
Edition (SSCE), so you must give it a reference to it wherever you may use it in code so
the compiler will know what you're talking about. For simplicity sake, we will do all of
our coding in the code behind of ‘Form1’. To access this, I simply double-click in design
view of ‘form1’ to access the code behind for ‘Form1’. Here you can see I've added a
reference, as shown in the using statement, to SQL Server Compact Edition. Also you
can see I've added a private form variable of type ‘SqlCeConnection’ called
‘cnSQL_CE’. And I've also added a method call ‘CreateConnection’, which, go figure,
creates the connection to SQL Server Compact Edition. Since we're doing this with a
variable that is global to the form, this variable will be available to other items in the
form’s code as a local variable. Also, to clean up after ourselves, and keep the system
happy, I have added to the form a close event a call for the SQL Server connection
variable to run it’s close method, which will close it’s connection to the database.
Now that we've created a connection, in code it least, to the database, it would help if
we actually created a table for the
database. So let's do that now. Go to
the Server Explorer, then select your
new database as I have done, then
right-click on it, and then click and
choose 'Create Table’. This takes you
to the next screen, as seen below.

Here you have the opportunity to add in your database fields. I have added an identity
column named ‘ID’, as well as another column named ‘WeekDayName’ for our
weekday. When you are done, simply hit the ‘OK’ button.
Now you’ve got a database table for SSCE. Let's put it to use. Now add code to add a
record to the database. First, we need an event for the record to be added, so let's go to
the click event for ‘btnInsert’ by double-clicking on the button marked ‘Insert’ on our
form to access it’s click event. After doing this works most of the code view for the click
event. Here we will add the code as seen below.

So, now all we need to do is run our program, type in a weekday into the textbox, and
then hit the insert button. This will then add a new record to the table. I put in the textbox
the value of “Monday”.

After you've done this, you can go to Server Explorer and see the new data. But, to do
so, you need to create another connection to the database. This time, it needs to point to
the application’s ‘bin’ directory, as that is where I have coded for the database operations
to be performed. The original connection we made to our SSCE data is to a copy which
resides in the same directory as our source code. When we created the database, the
system automatically made a copy of the database in the source code directory and places
it, the copy, into the ‘bin’ directory.

After that’s done, we can see our data in


the database table like this:
So, now, it may be nice to be able to see what data is in the table without having to go
to this length of trouble. This is the ‘R’ in our CRUD – Read. So let's now add code and
functionality for a ‘Select’ button. Add a button, whose text property is ‘Select’, and I'm
going to give mine the name of ‘btnSelect’. Next, let's add code for our button to create a
DataTable from the data in our table. Then, set the textboxes’ text property equal that
which it finds in the first row of the DataTables’ ‘WeekDayName’ field. Here's the code
for that below:

So, when your application gets to the code for the ‘Select’ button, it will query the
database, and get all the data in our new table and put that into a DataTable. It gets the
data from our created SqlCeCommand object which uses are global variable connection
of ‘cnSQL_CE’. Then we use the SQLCeDataAdapter variable we created to fill the
DataTable with our data. Then our code puts into a string variable what it finds in the first
row of the table from the ‘WeekDayName’ field. Of course, there's a lot of problems with
the way this is written, from a technique point of view. We have no Try/Catch handling
for the database access, nor do we have any accommodation if there is not a record in the
database table. This would cause an error message to come up if there was no data in the
table. But, as this is an article on SSCE CRUD, I am not worrying about, nor addressing,
those issues in detail. The payoff to all this is you should see when you rerun your
program, then hit the ‘Select’ button, your form should look like this:
Now is the time for our ‘U’ part of CRUD – Update.
First, let’s add another button to our form, whose text property is ‘Update’ and name is
‘btnUpdate’. Next, double-click on the newly created update button and add the code you
see below.

As before, I have to add a few caveats to this code. As you could probably see, it is
hardcoded only to update the record, whose ID is equal to ‘1’. Of course, if you did not
have an ID, which met this parameter, the update will fail. A much better way of doing
this would be to programmatically set the ID of the record you would like to update, but
as said before, this is an article on CRUD, and I am not worrying, nor covering such
specifics. You can see in the code, as we had used in the Insert method, we are using the
‘SqlCeCommand’ object variable to carry out the update, and also using our global SSCE
database connection, ‘cnSQL_CE’.

Last on our list, we have ‘D’, the Delete in CRUD


As before, add a new button to your form, set it’s text property to the value ‘Delete’,
and it’s name property to ‘btnDelete’. Next, add the following code you see below. You
will notice the reappearance of our friend the ‘SqlCeCommand’ object, which will be
used to carry out our delete SQL statement in the same manner as we just carried out our
update.

Now a few caveats, as before. In this example as well, we've hardcoded the ID of the
record we are deleting. In a real world application, of course, this would not be
acceptable, but for the use of this article it shows how the delete operation can be
performed.

Well, you've made it. You've seen how to create a SQL Server Compact Edition 2005
database from scratch, set it to use 128 bit encryption, assign a password to the database,
add a new table to the database, and how to build a Windows form application that allows
you to add records, select and show records, update records, and delete records. That's a
lot.

There are some limitations with SSCE, though. One of them is it cannot be used in web
applications. Microsoft has IIS, or SSCE, configured, where they will not allow a SSCE
database to operate in a web application. Microsoft strongly recommends, instead, a full
instance of SQL Server to be used, of any version from say, SQL Server Express on up.
So, don't get excited and think you will be able to do web applications with SSCE,
because those hopes will only be dashed with failure. SSCE is made for strictly Windows
applications only.

Also, SSCE does not support stored procedures.

But, clearly, there are a great number of things you can do in Windows applications
with SSCE. It is a giant leap forward from what we have had available previously. I
would very strongly recommend the full version of SQL Server or any applications which
are two tier, or more, to use SQL Server full edition, but for single tier applications I
think SQL Server Compact Edition is great.

Deployment
As far as deployment is concerned, Microsoft has a ‘msi’ install file available to load
on the client for the use of SQL Server Compact Edition. But, being the control freak that
I am, I like to add the necessary files to the application’s runtime directory, instead.
Here's a list of the files needed for successful deployment of a SSCE application.

 System.Data.SqlServerCe.dll
 sqlceca30.dll
 sqlcecompact30.dll
 sqlceer30en.dll
 sqlceme30.dll
 sqlceoledb30.dll
 sqlceqp30.dll
 sqlcese30.dll

FYI. On my computer, the only one that was natively in my application’s directory was
‘System.Data.SqlServerCe.dll’. The rest were in a directory below my VisualStudio
installation called ‘\Common7\IDE’.