1

I am trying to create a wrapper class for creating a database.

I want the database to be created and destroyed in code by the use of create and delete functions.

I read online that using DROP DATABASE will destroy the database however I cannot check that I have interpreted the information correctly as I have been unable to write a create function.

The examples I have found are all for .mdf databases that include servers.

My database will be only used locally and will contain a single data table.

The database will be populated on creation by a data file chosen by the user.

Below is the class I have begun writing.

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlServerCe;
using System.Windows.Forms;
using System.IO;

namespace DatabaseForm
{
    class DatabaseManager
    {

        private SqlCeConnection _sqlConnection;
        private string _cacheDatabase;
        private string _password;

        /// <summary>
        /// 
        /// </summary>
        public DatabaseManager()
        {
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private string ConnectionString()
        {
            return string.Format("DataSource=\"{0}\"; Password='{1}'", this._cacheDatabase, this._password);
        }

        /// <summary>
        /// 
        /// </summary>
        private void Open()
        {
            if (_sqlConnection == null)
            {
                _sqlConnection = new SqlCeConnection(this.ConnectionString());
            }

            if (_sqlConnection.State == ConnectionState.Closed)
            {
                _sqlConnection.Open();
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void Close()
        {
            if (_sqlConnection != null)
            {
                if (_sqlConnection.State == ConnectionState.Open)
                {
                    _sqlConnection.Close();
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public void CreateDatabase(string dbname, string password)
        {
            string strCommand;
            try
            {
                Open();
                strCommand = "CREATE DATABASE " + dbname;
                SqlCeCommand sqlCommand = new SqlCeCommand(strCommand, _sqlConnection);
                sqlCommand.ExecuteNonQuery();
                Close();

                _cacheDatabase = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + dbname;
                _password = password;
            }
            catch (Exception exc)
            {
                MessageBox.Show("Error in CreateDatabase(): " + exc.Message);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public void Delete()
        {
            string strCommand;
            try
            {
                Open();
                strCommand = "DROP DATABASE MyTable";
                SqlCeCommand sqlCommand = new SqlCeCommand(strCommand, _sqlConnection);
                sqlCommand.ExecuteNonQuery();
                Close();
            }
            catch (Exception exc)
            {
                MessageBox.Show("Error in Delete(): " + exc.Message);
            }
        }
    }
}

I want to get this working before I worry about how the class could fail. I will add defensive code at a later date.

So the area of issue is to do with the SqlCeConnection. What does the connection string need to be in order to create a database?

Once the database has been created I can use:

_cacheDatabase = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\MyDatabase.sdf";
_password = "";
string.Format("DataSource=\"{0}\"; Password='{1}'", _cacheDatabase, _password);

However MyDatabase.sdf does not exists until after CREATE DATABASE has been called.

Therefore what is the connection string?

6
  • 2
    Saying you are unable to create a database isn't enough. What issues do you have? Any errors/exceptions etc? Commented Dec 23, 2014 at 11:01
  • Do you definitely want a database? Often it's better to just use files + keep stuff in memory if you dont need multi-user stuff Commented Dec 23, 2014 at 11:06
  • Was just about to say, it isn't entirely clear what you are asking. If you look through your question you will actually notice, that there is not actually a question present through the entirety of your text. Can you clarify what the problem with your class is? Commented Dec 23, 2014 at 11:08
  • What is the syntax required to create a database? The problem is with the CreateDatabase function. You can see from this there is no value in _sqlConnection. It complains about this value being blank. However I also think the actual strCommand value is incorrect. I am using a database because there are going to be upwards of 20000 records. The user will then need the ability to filter the records and only display those that are required. I could write classes to do this however a database provides all the filter logic for me. Commented Dec 23, 2014 at 11:14
  • @PeterLillevold - yeah I also found this page. However it is for a server database. My database will only run locally. It also has lines included about log on which I don't need. If I knew more about sql I might be able to interpret/modify the syntax but I don't yet, so I can't! Commented Dec 23, 2014 at 11:54

2 Answers 2

1

Why bother with "DROP DATABASE". When using SQL Server CE, your database is one single file. It is enough to delete the file.

Sign up to request clarification or add additional context in comments.

2 Comments

No reason other than consistency as sql is how I will probably create the database. That was the command I had read to delete a database via sql. One strange thing does happen however if you just delete though... If you right click on solution explorer in visual studio and add a local database to the project it will prompt you for the type (dataset or entity). However if you delete that database, then add a second database the same way with the same name; it does not prompt you for database type...
Sure. Well, CE is special, so expect special behavior :)
0

If you really want to DROP/CREATE a database like that then the easiest way to get the scripts right would be to create a sample database in the SQL Management Studio then right click on the database and select Tasks > Generate Scrips....

There are plenty of options to choose and among them also a DROP/CREATE one. Then all you need to care is how to execute the scripts.

2 Comments

This is a question about SQL Server Compact Edition. Databases will have to be created/dropped at runtime on the phone/device
It doesn't really matter. The SQL for creating the database would be the same (I guess) so why bother writing the scrips manually if you can create a sample database in the management studio and let it generate the scripts for you? I know it's about a Compact Edition. I just wanted to show an easier way for creating the scripts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.