Programmers often need to create databases programmatically. This article describes how to use ADO.NET and Visual Basic .NET to programmatically create a Microsoft SQL Server database.
- Create a new Visual Basic .NET Windows Application project. Form1 is added to the project by default.
- Place a Command button on Form1, and change its Name property to btnCreateDatabase and its Text property to Create Database.
- Copy and paste the following line of code into Form1's "general declaration" section:
- Copy and paste the following code after the region "Windows Form Designer generated code":
Private Sub btnCreateDatabase_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnCreateDatabase.Click
Dim str As String
Dim myConn As SqlConnection = New SqlConnection("Server=(local)\netsdk;" & _
str = "CREATE DATABASE MyDatabase ON PRIMARY " & _
"(NAME = MyDatabase_Data, " & _
" FILENAME = 'D:\MyFolder\MyDatabaseData.mdf', " & _
" SIZE = 2MB, " & _
" MAXSIZE = 10MB, " & _
" FILEGROWTH = 10%) " & _
" LOG ON " & _
"(NAME = MyDatabase_Log, " & _
" FILENAME = 'D:\MyFolder\MyDatabaseLog.ldf', " & _
" SIZE = 1MB, " & _
" MAXSIZE = 5MB, " & _
" FILEGROWTH = 10%) "
Dim myCommand As SqlCommand = New SqlCommand(str, myConn)
MessageBox.Show("Database is created successfully", _
"MyProgram", MessageBoxButtons.OK, _
Catch ex As Exception
If (myConn.State = ConnectionState.Open) Then
- Change the connection string to point to your SQL Server, and make sure that the Database argument is set to Master or blank.
- Press F5 or CTRL+F5 to run the project, and then click Create Database.
- This code creates a custom database with specific properties.
- The folder that will 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 SQL Server's Model database and in the default location, then change the str variable in the code:
str = "CREATE DATABASE MyDatabase"
For additional information on the CREATE DATABASE Transact-SQL command, see the SQL Server Books Online or MSDN Online Library:
Accessing Data with ADO.NET
Article ID: 305079 - Last Review: Oct 16, 2012 - Revision: 1
Microsoft ADO.NET 1.1, Microsoft Visual Basic .NET 2003 Standard Edition, Microsoft Visual Basic .NET 2002 Standard Edition