You are on page 1of 2

Create a sql server database programmatically at run time about:reader?url=http://stackoverflow.com/questions/25011969/create-...

stackoverflow.com

The following code will help you to create a database named my_db and a table within the database named
as customer.

Note: necessary explanations are given in comments please read it for clarification

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button1.Click
//creating and initializing the connection string
Dim myConnectionString As SqlConnection = New SqlConnection("Data
Source=(local)\SQLEXPRESS;Initial Catalog=master;Integrated Security=True;
Pooling=False")
//since we need to create a new database set the Initial Catalog
as Master
//Which means we are creating database under master DB
Dim myCommand As String //to store the sql command to be executed
myCommand = "CREATE database my_db" //the command that creates new
database
Dim cmd As SqlCommand = New SqlCommand(myCommand,
myConnectionString) // creating command for execution
Try
cmd.Connection.Open() //open a connection with cmd
cmd.ExecuteNonQuery() //Execute the query
cmd.Connection.Close() //Close the connection
Catch
MsgBox(" Already installed database", MsgBoxStyle.Critical, "
MaS InfoTech- Warning")
End Try
//Creating table to the dynamicaly created database
Try
Dim cn As SqlConnection = New SqlConnection("Data Source=
(local)\SQLEXPRESS;Initial Catalog=my_db;Integrated Security=True;
Pooling=False")
//here the connection string is initialized with Initial Catalog
as my_db
Dim sql As String //sql query string
sql = "CREATE TABLE customer(cus_name varchar(50) NULL,address
varchar(50) NULL,mobno numeric(18, 0) NULL,tin varchar(50) NULL,kg
varchar(50) NULL)"
cmd = New SqlCommand(sql, cn) // create command with

1 of 2 24-Jan-17 16:18
Create a sql server database programmatically at run time about:reader?url=http://stackoverflow.com/questions/25011969/create-...

connection and query string


cmd.Connection.Open()
cmd.ExecuteNonQuery()
cmd.Connection.Close()
Catch
MsgBox(" Already installed database", MsgBoxStyle.Critical, "
MaS InfoTech- Warning")
End Try
End Sub

2 of 2 24-Jan-17 16:18

You might also like