2016-06-17 66 views
0

我是新来的。最近我被老板命令从Winforms应用程序创建SQL Server数据库。我试图以编程方式创建数据库。但每次我收到错误消息。如何从C#以编程方式创建SQL Server数据库文件(.mdf)?

enter image description here

是否有可能创建一个SQL Server数据库文件(.mdf)编程?

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Data.SqlClient; 

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

     private void btnCreateDatabase_Click(object sender, EventArgs e) 
     { 
      String str; 
      SqlConnection myConn = new SqlConnection("Data Source =(LocalDB)\\MSSQLLocalDB; Integrated security =SSPI;database=master"); 
     str = "CREATE DATABASE ss ON PRIMARY " + 
      "(NAME = ss_Data, " + 
      "FILENAME = 'D:\\ss.mdf', " + 
      "SIZE = 3MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " + 
      "LOG ON (NAME = ss_Log, " + 
      "FILENAME = 'D:\\ss.ldf', " + 
      "SIZE = 1MB, " + 
      "MAXSIZE = 5MB, " + 
      "FILEGROWTH = 10%)"; 

     SqlCommand myCommand = new SqlCommand(str, myConn); 

     try 
     { 
      myConn.Open(); 
      myCommand.ExecuteNonQuery(); 
      MessageBox.Show("DataBase is Created Successfully", "MyProgram",  MessageBoxButtons.OK, MessageBoxIcon.Information); 
     } 
     catch (System.Exception ex) 
     { 
      MessageBox.Show(ex.ToString(), "MyProgram", 
MessageBoxButtons.OK, MessageBoxIcon.Information); 
     } 
     finally 
     { 
       if (myConn.State == ConnectionState.Open) 
       { 
        myConn.Close(); 
       } 
     } 
    } 
} 

问题在哪里我的代码?

+0

访问被拒绝是非常有帮助的。您无权在尝试创建文件的位置创建文件。 – LarsTech

+0

我发表了这个评论作为答案,所以请参考 – Justin

+0

我也使用了另一个位置。但它显示了同样的错误。 –

回答

2

错误消息表明SQL服务器无法在'D:'驱动器上创建文件。确保SQL服务器运行的用户具有该驱动器所需的映射和访问权限。

+0

我试图将数据库保存到驱动器的其余部分。但它显示相同的错误消息。 –

+0

这不是你需要许可的人。这是SQL服务器。查看您的services.msc并查看正在运行的用户SQL Server。这是需要许可的用户。 – GWLlosa

0

是的。

您可以使用SQL Server Managments Objects

//Connect to the local, default instance of SQL Server. 
Server srv = new Server(); 

// Define a Database object variable by supplying the server and the 
// database name arguments in the constructor. 
Database db = new Database(srv, "Test_SMO_Database"); 

//Create the database on the instance of SQL Server. 
db.Create(); 

//Reference the database and display the date when it was created. 
db = srv.Databases["Test_SMO_Database"]; 
Console.WriteLine(db.CreateDate); 
+0

我很新编程。我不明白你的答案先生。 –

0

我建议首先在运行Visual Studio为管理员。右键单击Visual Studio图标并选择“以管理员身份运行”。

我也建议在这里实现了答案:How to request administrator permissions when the program starts?

这是为了确保你的应用程序将需要它的机器上运行,它通常需要如果创建/删除文件的管理员权限。

编辑:如果在Visual Studio以管理员身份运行时仍然无法访问驱动器,则可能是该驱动器上的Window权限,而不是您项目的任何问题。

相关问题