使用Visual Studio在运行时创建本地数据库

时间:2016-02-09 12:51:15

标签: c# sql-server vs-community-edition

初学者的问题 - 我可以请求在运行时以编程方式创建本地数据库文件的建议。我希望以后能够使用Windows资源管理器以与文本和其他文件相同的方式重命名,删除它们等,并将它们复制到其他计算机。

这是使用带有C#的Visual Studio Community 15,安装了SQL Server Data Tools 14.0.50616.0。该计算机具有Microsoft SQL Server 2014。

举个例子,我删除了程序的剩余部分以留下下面的代码,该代码使用带有3个按钮的Windows窗体应用程序(btnCreateDbbtnDeleteDbbtnDoesDbExist)和组合框cbxDb作为数据库名称。它使数据库位于现有文件夹C:\DbTemp

它显然会创建和删除新数据库并生成文件,例如文件夹中的mydb1.mdfmydb1.ldf,并声明它们存在。但是,如果我使用资源管理器删除这两个文件,如果尝试删除或创建数据库,则会抛出异常;并且btnDoesDbExist表明它仍然存在。

为什么Windows资源管理器删除文件后数据库仍然存在? btnDoesDatabaseExist下的代码没有引用文件的路径,所以它必须看到别的东西,但在哪里?这是程序用户创建,删除和检测这些数据库的正确方法吗?

using System;
using System.Data;
using System.Windows.Forms;

//my additions
using System.Data.SqlClient;

namespace DataProg15
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public static string form1ConnectionString = "Data Source = (LocalDB)\\MSSQLLocalDB; Integrated Security = True; Connect Timeout = 30; ";
    private string form1DatabasePath = "C:\\DbTemp";

    private void btnCreateDb_Click(object sender, EventArgs e)
    {
        string nameToCreate = cbxDb.Text;
        SqlConnection myConn = new SqlConnection(form1ConnectionString);

        string str = "CREATE DATABASE " +nameToCreate+ " ON PRIMARY " +
            "(NAME = " +nameToCreate+ "_Data, " +
            "FILENAME = '" +form1DatabasePath+ "\\" +nameToCreate+ ".mdf', " +
            "SIZE = 4MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
            "LOG ON (NAME = " +nameToCreate+ "_Log, " +
            "FILENAME = '" +form1DatabasePath+ "\\" +nameToCreate+ ".ldf', " +
            "SIZE = 1MB, " +
            "MAXSIZE = 5MB, " +
            "FILEGROWTH = 10%)";

        SqlCommand myCommand = new SqlCommand(str, myConn);

        try
        {
            myConn.Open();
            myCommand.ExecuteNonQuery();
            MessageBox.Show("DataBase '" + nameToCreate + "' was created successfully");
        }
        catch (System.Exception ex)
        {
            MessageBox.Show("Exception in CreateDatabase " + ex.ToString(), "Exception in CreateDatabase", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        finally
        {
            if (myConn.State == ConnectionState.Open)
            {
                myConn.Close();
            }
        }
    }


    private void btnDeleteDb_Click(object sender, EventArgs e)
    {
        string nameToDelete = cbxDb.Text;
        string myConnectionString = form1ConnectionString + "AttachDBFileName = " + form1DatabasePath + "\\" + nameToDelete + ".mdf ";
        string str = "USE MASTER DROP DATABASE " + nameToDelete;

            SqlConnection myConn = new SqlConnection(myConnectionString);
            SqlCommand myCommand = new SqlCommand(str, myConn);
            myConn.Open();

            try
            {
                myCommand.ExecuteNonQuery();
                MessageBox.Show("DataBase '" + nameToDelete + "' was deleted successfully");

            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Exception in DeleteDatabase '" +nameToDelete+ "'", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                if (myConn.State == ConnectionState.Open)
                {
                    myConn.Close();
                }
            }
    }

    private void btnDoesDbExist_Click(object sender, EventArgs e)
    {
        string nameToTest = cbxDb.Text;
        using (var connection = new SqlConnection(form1ConnectionString))
        {
            using (var command = new SqlCommand(string.Format(
                   "SELECT db_id('" +nameToTest+ "')", nameToTest), connection))
            {
                connection.Open();

                if ((command.ExecuteScalar() != DBNull.Value))
                {
                    MessageBox.Show("DataBase '" +nameToTest+ "' exists");
                }
                else
                {
                    MessageBox.Show("Database '" +nameToTest+ "' does not exist");
                }
            }
        }

    }
}

}

感谢大家的回复,非常感谢您的麻烦。

我现在明白我使用的是错误的数据库,所以我尝试使用SQL Server Compact代替。已卸载,重新下载并重新安装SQL Server Compact,包括SP1。还从SQL Server Compact/SQLite Toolbox下载并安装了https://visualstudiogallery.msdn.microsoft.com/0e313dfd-be80-4afb-b5e9-6e74d369f7a1。但是当我键入using System.Data.SqlServerCe时,Visual Studio始终显示错误。此外,当我输入SqlCeEngineSqlCecommand时,我会假设出于同样的原因。

在Visual Studio中,SQL Server Data ToolsSQL Server Compact & SQLite Toolbox显示为已安装的产品,但不显示为SQL Server Compact。我是否需要将其安装到Visual Studio中,如果是这样,它是如何完成的?

2 个答案:

答案 0 :(得分:2)

Solution Explorer下的References下,检查是否列出了System.Data.SqlServerCe。如果没有,请右键点击References然后Add Reference - > Browse按钮并选择文件System.Data.SqlServerCe.dll,可能在C:\Program Files\Microsoft SQL Server Compact Edition\v4.0\Desktop中。 System.Data.SqlServerCe现在应显示在References下。

以下程序似乎有效,而且更简单。感谢所有人的帮助。

using System;
using System.Data;
using System.Windows.Forms;
//my additions
using System.Data.SqlServerCe;
using System.IO;

namespace DataProg15
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public static string form1DatabasePath = "C:\\DbTemp\\dbtemp1.sdf";
        public static string form1ConnectionString = "Data Source = " +form1DatabasePath;

        private void btnCreateDb_Click(object sender, EventArgs e)
        {
                SqlCeEngine engine = new SqlCeEngine(form1ConnectionString);
            try
            {
                engine.CreateDatabase();
                MessageBox.Show("DataBase '" +form1DatabasePath+ "' was created successfully");
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Exception in CreateDatabase " + ex.ToString(), "Exception in CreateDatabase", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally
            {
                engine.Dispose();
            }
        }

        private void btnDeleteDb_Click(object sender, EventArgs e)
        {
            if (File.Exists(form1DatabasePath))
            {
                try
                {
                    File.Delete(form1DatabasePath);
                    MessageBox.Show("DataBase '" +form1DatabasePath+ "' was deleted successfully");
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.ToString(), "Exception in DeleteDatabase '" +form1DatabasePath+ "'", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }

        private void btnDoesDbExist_Click(object sender, EventArgs e)
        {
            if (File.Exists(form1DatabasePath))
            {
                    MessageBox.Show("DataBase '" +form1DatabasePath+ "' exists");
            }
            else
            {
                    MessageBox.Show("DataBase '" +form1DatabasePath+ "' does not exist");
            }
        }
    }
}

答案 1 :(得分:0)

如果该数据库处于活动状态,SQL Server将不允许您删除数据库的物理文件 - 永远。唯一能够做到这一点的是数据库是否为DETACHED(如前所述)

所以我怀疑你告诉我们的事情是不是很正确?

我会更改您的"检查数据库是否存在"逻辑;

  

从sys.databases中选择*,其中name =' yourdatabasename'

当你删除数据库时,无论如何我都会运行这个查询,只是为了查看它返回的内容。

相关问题