以编程方式创建数据库(没有权限?)

时间:2016-07-11 17:09:59

标签: c# sql database connection-string

我正在尝试以编程方式创建一个新数据库(.mdf文件),并最终在数据库中创建表。我不确定要使用什么连接字符串,我看到下面的代码中的一个在多个站点上抛出几次。我在执行时遇到错误:

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: CREATE DATABASE permission denied in database 'master'.

以下是我正在运行的用于创建数据库的代码:

string filename = "C:\\AnalysisResultsDatabase.mdf";
string databaseName = Path.GetFileNameWithoutExtension(filename);

using (var connection = new SqlConnection("Server=localhost;Integrated security=SSPI;database=master"))
{
    connection.Open();
    using (var command = connection.CreateCommand())
    {
        command.CommandText = String.Format("CREATE DATABASE {0} ON PRIMARY (NAME={0}, FILENAME='{1}')", databaseName, filename);
        command.ExecuteNonQuery();

        command.CommandText = String.Format("EXEC sp_detach_db '{0}', 'true'", databaseName);
        command.ExecuteNonQuery();
    }
}

2 个答案:

答案 0 :(得分:0)

这可能是由于SQL Server实例服务标识没有对磁盘上MDF文件位置的权限。

只是为了检查,尝试将服务标识更改为LocalSystem(如果它尚未设置为该帐户)。

答案 1 :(得分:0)

Your domain account that you are logging into does not have the appropriate permissions for CREATE DATABASE. You'll have to contact an administrator who has enough permissions to grant them to you before you can create databases.