如何从C#以编程方式创建SQL Server数据库文件(.mdf)?

时间:2016-06-17 16:35:25

标签: c# sql-server database winforms

我刚接触到这里。最近我被老板命令从Winforms应用程序创建一个SQL Server数据库。我试图以编程方式创建数据库。但每次我收到错误信息。

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();
                }
        }
    }
}

我的代码出现问题在哪里?

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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);  

答案 2 :(得分:0)

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

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

这样,您的应用程序将需要管理员访问它运行的计算机,如果它正在创建/删除文件,通常需要它。

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