2016-06-17 70 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權限,而不是您項目的任何問題。

相關問題