5

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

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

例如,我删除了程序的多余部分以保留下面的代码,该代码使用带有 3 个按钮( 、 和 )的 Windows 窗体应用程序btnCreateDbbtnDeleteDb一个btnDoesDbExist用于cbxDb数据库名称的组合框。它在现有文件夹中创建数据库C:\DbTemp

mydb1.mdf它显然会创建和删除一个新数据库并制作文件,例如mydb1.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 Toolboxhttps://visualstudiogallery.msdn.microsoft.com/0e313dfd-be80-4afb-b5e9-6e74d369f7a1. 但是当我输入using System.Data.SqlServerCe. 同样,当我输入SqlCeEngineor时SqlCecommand,我假设也是出于同样的原因。

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

4

2 回答 2

2

Solution Explorer下面References,检查System.Data.SqlServerCe是否列出。如果没有,请右键单击Referencesthen 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");
            }
        }
    }
}
于 2016-02-12T14:03:19.057 回答
0

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

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

我会将您的“检查数据库是否存在”逻辑更改为;

select * from sys.databases where name = 'yourdatabasename'

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

于 2016-02-09T14:26:11.760 回答