Click here to Skip to main content
15,880,364 members
Articles / Database Development / SQL Server
Tip/Trick

Creating a SQL Server Database Programmatically

Rate me:
Please Sign up or sign in to vote.
5.00/5 (9 votes)
14 Aug 2010CPOL 37.3K   11   11
A simple example of creating a new database on a SQl Server instance
Recently I asked in the Forums for help in creating a new database on a SQL Server from within my application. I thought this would be helpful when I installed a custom app at work, where I don't have access to the server, but have permissions to administer the SQL Server 2008 service.

I received a number of helpful suggestions, but they all boiled down to "you can't do it." I hate being told "No" so I searched some more. MSDN was useless, and Google not much better, but I finally found an answer in the Microsoft Technical Support Knowledge Base.

Just in case someone else is looking for a way to do this simple task, I offer the following simple code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

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

        private void btnCreateDatabase_Click(object sender, EventArgs e)
        {
            String str;
            SqlConnection myConn = new SqlConnection
                ("Server=BAAL\\SQLEXPRESS2;Integrated security=SSPI ;database=master");
            str = "CREATE DATABASE MyDatabase";
            SqlCommand myCommand = new SqlCommand(str, myConn);
            try
            {
                myConn.Open();
                myCommand.ExecuteNonQuery();
                MessageBox.Show("Database Created Successfully", "MyApp", 
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString(), "MyApp", MessageBoxButtons.OK, 
                    MessageBoxIcon.Information);
            }
            finally
            {
                if (myConn.State == ConnectionState.Open)
                {
                    myConn.Close();
                }
            }

        }
    }
}


I apologize for the formatting - Opera is a bit user-hostile in that respect.

Your app must be running under an account that has full privileges on the server for this to work, and you'll need to modify the connection string to match your installation, of course. But this worked perfectly on the first attempt, and I thought it worth sharing.

License

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


Written By
Engineer Retired
United States United States
BS Electrical & Electronics Engineering

Thirteen years experience designing & programming measurement & control instrumentation.

Retired two years ago from the Tribal Utility I was working for, designing power, water, and sewer systems for the reservation, and managing the construction and maintenance of same. Now working as a gun salesman and smith, as well as doing metal machining and welding for fun and too little profit.I recently bought 20 acres of land, and a tractor to help me develop it into a homesite and ranch. I was planning to raise lobsters, but having seen frozen rabbits on Amazon selling for $49 each, I may have to replan.

Programming experience using assembly, FORTRAN, BASIC, HP JCL, Prolog, Ada, Pascal, hpl, ; currently learning VC# and having "fun" with ASP.Net.

Avid darts player, though not a good one... Fair to excellent 12-string guitar player, depending on who you ask. Spare time spent fishing, reading, and playing with the neighbor's cat (see picture). Second degree black belts in Hapkido and Taekwondo.

Past President of the local Kiwanis Club, past Director of the United Way, and no longer a member of either.

Have held licenses as a Real Estate broker and Securities dealer - once ordained as a minister on a whim. My latest certificate was earned without any hands on experience at all - Yamaha Certified 5-Star Technician for motorcycles, ATVs, and watercraft. What next?

Raised in sunny California, before it became the Peoples' Republic of California. Relocated to Arizona to escape being homeless after peace broke out.


Objective: To learn all there is to know. I know I'll be disappointed one day, but I've made a good start, and the eventual disappointment is likely to be brief.


Comments and Discussions

 
QuestionInstance of an Existing Database Pin
Raoof Ahmed Khan16-Sep-15 4:13
Raoof Ahmed Khan16-Sep-15 4:13 
AnswerRe: Instance of an Existing Database Pin
Roger Wright16-Sep-15 18:00
professionalRoger Wright16-Sep-15 18:00 
QuestionThanks Pin
Raoof Ahmed Khan21-Jun-15 23:54
Raoof Ahmed Khan21-Jun-15 23:54 
AnswerRe: Thanks Pin
Roger Wright22-Jun-15 4:36
professionalRoger Wright22-Jun-15 4:36 
QuestionNot at all Pin
PCOMM Engineering17-Sep-14 11:17
PCOMM Engineering17-Sep-14 11:17 
AnswerRe: Not at all Pin
Roger Wright17-Sep-14 15:25
professionalRoger Wright17-Sep-14 15:25 
GeneralReason for my vote of 5 This code helped me to what it says ... Pin
MichaelSwede13-Apr-11 5:37
MichaelSwede13-Apr-11 5:37 
GeneralThis is a sample of how to do it, not production code, of co... Pin
Roger Wright16-Aug-10 16:13
professionalRoger Wright16-Aug-10 16:13 
GeneralSorry ! its not good bcoz when u'll press on create button t... Pin
Niyamat16-Aug-10 1:35
Niyamat16-Aug-10 1:35 
GeneralI don't write 'em, I just steals 'em from Microsoft. :-D Pin
Roger Wright14-Aug-10 10:39
professionalRoger Wright14-Aug-10 10:39 
GeneralThe str variable is needless, I'd instantiate the connection... Pin
PIEBALDconsult14-Aug-10 6:33
mvePIEBALDconsult14-Aug-10 6:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.