Reputation: 105
I'm new to here. Recently I was ordered by my boss to make a SQL Server database from a Winforms app. 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 ?
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?
Upvotes: 0
Views: 1399
Reputation: 553
I would suggest firstly running Visual Studio as administrator. Right click the Visual Studio icon and 'Run as Administrator'.
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.
Upvotes: 0
Reputation: 16854
Yes.
You can use 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);
Upvotes: 0
Reputation: 24403
The error message indicates that the SQL server was not able to create a file on the 'D:' drive. Make sure that the user the SQL server runs as has the necessary mappings and access rights to that drive.
Upvotes: 2