简体   繁体   English

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

[英]How can I create a SQL Server database file (.mdf) programmatically from C#?

I'm new to here. 我是新来的。 Recently I was ordered by my boss to make a SQL Server database from a Winforms app. 最近,我的老板命令我从Winforms应用程序创建SQL Server数据库。 I'm trying to create database programmatically. 我正在尝试以编程方式创建数据库。 But every time I'm getting an error message. 但是每次我收到一条错误消息时。

在此处输入图片说明

Is it possible to create a SQL Server database file ( .mdf ) programmatically ? 是否可以以编程方式创建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();
                }
        }
    }
}

Where is the problem with my code? 我的代码在哪里出问题?

The error message indicates that the SQL server was not able to create a file on the 'D:' drive. 该错误消息表明SQL Server无法在“ D:”驱动器上创建文件。 Make sure that the user the SQL server runs as has the necessary mappings and access rights to that drive. 确保SQL Server运行的用户具有对该驱动器的必要映射和访问权限。

Yes. 是。

You can use SQL Server Managments Objects 您可以使用SQL Server管理对象

//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);  

I would suggest firstly running Visual Studio as administrator. 我建议首先以管理员身份运行Visual Studio。 Right click the Visual Studio icon and 'Run as Administrator'. 右键单击Visual Studio图标,然后单击“以管理员身份运行”。

I would also suggest implementing the answer here: How to request administrator permissions when the program starts? 我也建议在这里实现答案: 程序启动时如何请求管理员权限?

This is so your application will require administrator access on the machine it is running on, which it will generally need if it is creating/deleting files. 这样一来,您的应用程序将需要管理员对其运行所在的计算机的访问权限,而在创建/删除文件时通常需要管理员访问权限。

Edit: If you still cannot access the drive when Visual Studio is running as administrator, then it is likely the Window's permissions on that drive, rather than any issue with your project. 编辑:如果在以管理员身份运行Visual Studio时仍然无法访问驱动器,则很可能是Windows在该驱动器上的权限,而不是项目的任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何以编程方式将.MDF文件附加到Azure SQL Server C# - How to attach .MDF file to Azure SQL Server programmatically c# 如何通过C#以编程方式在不使用.mdf或.ldf文件的情况下将.bak文件还原到新服务器? - How can I restore a .bak file to a new server without using the .mdf or .ldf files, programmatically with C#? 如何使用c#从文件系统和SQL Server中删除动态生成的数据库文件(.MDF和.LDF) - How to delete a dynamically generated database file (.MDF and .LDF) from the filesystem and from SQL server using c# 使用C#以编程方式创建SQL Server数据库 - Create SQL Server database programmatically with C# 我可以在没有 sql 服务器的情况下运行带有 mdf 文件的 C# windows 程序吗? - Can i run C# windows program with mdf file without sql server? 如何使用C#在SQL Server数据库中创建视图? - How can I create a view in a SQL Server database with C#? 如何在C#中以编程方式创建SQL Server数据库 - How to create a SQL Server database programmatically in C# 如何在C#中从mdf数据库下载文件 - how to download file from mdf database in c# 以编程方式分离SQL Server数据库以复制mdf文件 - Programmatically detach SQL Server database to copy mdf file 如何以编程方式备份​​SQL Server数据库(mdf)以便以后逐行导入它? - How to backup SQL Server database (mdf) programmatically to later import it rowwise?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM