简体   繁体   中英

Create a local database programmatically in c#

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM