dimanche 19 juin 2016

How can i create sql database(.mdf) programmatically from winform C#?

I'm new to here. Recently I was ordered by my boss to make a sql databased winform. I'm trying to create database programmatically . But every time I'm getting an error message.

enter image description here

Is it possible to create sql database 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();
                }
            }
        }
    }
}

Above is my code. Where is the problem??

Aucun commentaire:

Enregistrer un commentaire