简体   繁体   English

在C#中以编程方式创建本地数据库

[英]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. 我希望通过使用create和delete函数在代码中创建和销毁数据库。

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. 我在线阅读了使用DROP DATABASE会破坏数据库的信息,但是由于无法编写create函数,因此无法检查是否正确解释了信息。

The examples I have found are all for .mdf databases that include servers. 我发现的示例全部用于包含服务器的.mdf数据库。

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. 因此,问题所在与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. 但是,直到调用CREATE DATABASE后,MyDatabase.sdf才存在。

Therefore what is the connection string? 因此,连接字符串是什么?

Why bother with "DROP DATABASE". 为什么要打扰“ DROP DATABASE”。 When using SQL Server CE, your database is one single file. 使用SQL Server CE时,数据库是一个文件。 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... . 如果您真的想要DROP / CREATE的数据库,那么正确获取脚本的最简单方法是在SQL Management Studio中创建示例数据库,然后右键单击该数据库,然后选择Tasks > Generate Scrips...

There are plenty of options to choose and among them also a DROP / CREATE one. 有很多选项可供选择,其中包括DROP / CREATE Then all you need to care is how to execute the scripts. 然后,您需要关心的是如何执行脚本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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