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?