我是新來的。最近我被老闆命令從Winforms應用程序創建SQL Server數據庫。我試圖以編程方式創建數據庫。但每次我收到錯誤消息。如何從C#以編程方式創建SQL Server數據庫文件(.mdf)?
是否有可能創建一個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();
}
}
}
}
問題在哪裏我的代碼?
訪問被拒絕是非常有幫助的。您無權在嘗試創建文件的位置創建文件。 – LarsTech
我發表了這個評論作爲答案,所以請參考 – Justin
我也使用了另一個位置。但它顯示了同樣的錯誤。 –