For a Microsoft Visual C++ .NET version of this article, see 307402 .
For a Microsoft Visual J# .NET version of this article, see 320628 .
This article refers to the following Microsoft .NET Framework Class Library namespace:
IN THIS TASK
To create the database, follow these steps:
- Create a new Visual C# .NET Windows application.
- Place a button on Form1. Change the button's Name property to btnCreateDatabase, and then change the Text property to Create Database.
- Use the using statement on the System and System.Data namespaces so that you do not have to qualify declarations in those namespaces later in your code. Add the following code to the General Declarations section of Form1:
- Switch to Form view, and then double-click Create Database to add the click event handler. Add the following sample code to the handler:
SqlConnection myConn = new SqlConnection ("Server=localhost;Integrated security=SSPI;database=master");
str = "CREATE DATABASE MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = 'C:\\MyDatabaseData.mdf', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = 'C:\\MyDatabaseLog.ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
catch (System.Exception ex)
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
if (myConn.State == ConnectionState.Open)
- Change the connection string to point to your computer running SQL Server, and then verify that the Database argument is set to Master or is blank.
- Press F5 or CTRL+F5 to run the project, and then click Create Database.
- Use the Server Explorer to verify that the database is created.
- This code creates a custom database with specific properties.
- The folder that is going to hold the created .mdf and .ldf files must already exist before you run the code or an exception will be generated.
- If you want to create a database that is similar to the SQL Server Model database, and you want the database in the default location, then change the str variable in the code, as in the following sample code:
str = "CREATE DATABASE MyDatabase"
Article ID: 307283 - Last Review: Mar 23, 2009 - Revision: 1