Click here to Skip to main content
15,892,298 members
Articles / Mobile Apps / Windows Mobile

Create a SQL Database Programmatically

Rate me:
Please Sign up or sign in to vote.
3.49/5 (18 votes)
24 Oct 2008CPOL2 min read 104.7K   4.1K   57  
In this article, I will explain how to use Microsoft SQL Management Objects (SMO) to create a Microsoft SQL database from C# code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;


namespace CreateDB
{
    public partial class CreateDB : Form
    {
        public CreateDB()
        {
            InitializeComponent();
        }

        private string dbstring = string.Empty;

        private void CreateDB_Load(object sender, EventArgs e)
        {
            try
            {
                if (MessageBox.Show("Going to look for all SQL Server in the network this might take some time. Do you want to proceed", "SQL Servers", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                {
                    DataTable dt = SmoApplication.EnumAvailableSqlServers();
                    foreach (DataRow dr in dt.Rows)
                    {
                        this.cbServers.Items.Add(dr[0]);
                    }
                }
                StreamReader sr = new StreamReader("BTErrorManagerDBSchema.sql");
                dbstring = sr.ReadToEnd();
                sr.Close();

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                this.tbProgress.Text = ex.Message;
                this.tbProgress.ScrollToCaret();

            }
        }

        private void btnCreateDB_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            try
            {
                sb.AppendLine(string.Format("Starting to create {0} with login to {1}", this.tbDBName.Text, this.tbBTSAppUser.Text));
                sb.AppendLine("Connecting to DB Server");
                dbstring = dbstring.Replace(@"LIGHTWIDGETSVM\BizTalk Application Users", this.tbBTSAppUser.Text);
                this.tbProgress.Text = sb.ToString();
                this.tbProgress.ScrollToCaret();
                //Connect to the local, default instance of SQL Server.
                string srvname = this.cbServers.SelectedItem as string;
                Server srv;
                if (srvname == null)
                {
                    srv = new Server();
                    sb.AppendLine("Connected to local SQL server");
                }
                else
                {
                    srv = new Server(srvname);
                    sb.AppendLine(string.Format("Connected to {0}", srvname));
                }

                this.tbProgress.Text = sb.ToString();
                this.tbProgress.ScrollToCaret();
                //Define a Database object variable by supplying the server and the database name arguments in the constructor.
                Database db = srv.Databases[this.tbDBName.Text.Trim()];
                if (db != null)
                {
                    if (MessageBox.Show(string.Format("The '{0}' already exists do you want to drop it?", this.tbDBName.Text), "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        db.Drop();
                    }
                    else
                    {
                        if (MessageBox.Show(string.Format("Create the Tables and Stored Procedures for BT Error Manager on  '{0}'?", this.tbDBName.Text), "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            sb.AppendLine("Creating the Tables and Stored Procedures.");
                            this.tbProgress.Text = sb.ToString();
                            db.ExecuteNonQuery(dbstring);
                            sb.AppendLine(string.Format("Created the Tables and Stored Procedures for BT Error Manager on  '{0}'", this.tbDBName.Text));
                            this.tbProgress.Text = sb.ToString();
                            this.tbProgress.ScrollToCaret();

                        }
                        sb.AppendLine("Proceed or select another database");
                        this.tbProgress.Text = sb.ToString();
                        this.tbProgress.ScrollToCaret();
                        return;
                    }
                }
                sb.AppendLine("Creating the database.....");
                db = new Database(srv, this.tbDBName.Text);
                this.tbProgress.Text = sb.ToString();
                this.tbProgress.ScrollToCaret();
                //Create the database on the instance of SQL Server.
                db.Create();
                sb.AppendLine("Created the database.");
                sb.AppendLine("Creating the Tables and Stored Procedures.");
                this.tbProgress.Text = sb.ToString();
                this.tbProgress.ScrollToCaret();
                //'Reference the database and display the date when it was created.
                db.ExecuteNonQuery(dbstring);
                sb.AppendLine("Success!");
                this.tbProgress.Text = sb.ToString();
                this.tbProgress.ScrollToCaret();

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                sb.AppendLine("Failuer:" + ex.Message);
                this.tbProgress.Text = sb.ToString();
                this.tbProgress.ScrollToCaret();

            }

            sb.AppendLine("Proceed or select another database");
            this.tbProgress.Text = sb.ToString();
            this.tbProgress.ScrollToCaret();

        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
Canada Canada
As a well-established IT leader with a passion for architecture, design, coding, refactoring, and development, I possess 20+ years’ success spearheading large teams to deliver the end-to-end development of 30+ innovative software solutions on time and under budget on a US and international level.

Throughout my career, I have made it my priority to utilize current technologies and new techniques to develop elegant, creative technical solutions across all project phases. Comfortable in collaborative and independently-driven roles, I am a forward-thinking leader with refined analytical and critical thinking skills, and I can adapt and revise my strategies to meet evolving priorities, shifting needs, and emergent issues. As a dynamic leader with experience as Technical Lead and Senior Manager, as well as on the Board of Directors, I have led numerous teams to create a new employees experience with Workday, roadmap for people systems (JDA WFMR, Kronos, Infor, Workday, and monitoring with Splunk), and architecture for 20+ projects at Loblaw. Furthermore, I have spearheaded As a well-established IT leader with a passion for architecture, design, coding, refactoring, and development, I possess 20+ years’ success spearheading large teams to deliver the end-to-end development of 30+ innovative software solutions on time and under budget on a US and international level.

Throughout my career, I have made it my priority to utilize current technologies and new techniques to develop elegant, creative technical solutions across all project phases. Comfortable in collaborative and independently-driven roles, I am a forward-thinking leader with refined analytical and critical thinking skills, and I can adapt and revise my strategies to meet evolving priorities, shifting needs, and emergent issues. As a dynamic leader with experience as Technical Lead and Senior Manager, as well as on the Board of Directors, I have led numerous teams to create a new employees experience with Workday

Comments and Discussions