Create database with if not exists check

‘Creating basic connection-string to server
Dim sConnectionString As String = “server=” & server_ip & “;uid=” & user_id & “;pwd=” & password & “;database=”

‘Creating SQL-command object
Dim cmdNew As New SqlCommand

‘Creating connection to server
Dim cnConnection As New SqlConnection

‘Adding the connection-string to the connection
cnConnection.ConnectionString = sConnectionString

‘Creating sql-string to execute
Dim strSQL As String

‘Assigning connection to sql-command
cmdNew.Connection = cnConnection

‘Preparing SQL-string to check if database exists
strSQL = “SELECT count(*) as numbers FROM master..sysdatabases WHERE name=’” & database & “‘”

‘Adding the sql-command to sql-command object
cmdNew.CommandText = strSQL

Try

    ‘Opening SQL-connection
    cnConnection.Open()

    If cmdNew.ExecuteScalar > 0 Then

‘The database already exists
MessageBox.Show(“Database already exists.”, “Information”, MessageBoxButtons.OK, MessageBoxIcon.Information)

    Else
‘Preparing SQL-string to create database
strSQL = “IF NOT EXISTS (Select * From master..sysdatabases Where Name = ‘” & database & “‘) CREATE DATABASE ” & database

‘Adding the SQL-string to the SQL-command
cmdNew.CommandText = strSQL

‘Executing SQL-query
cmdNew.ExecuteNonQuery()

‘Everything went well..
MessageBox.Show(“Database created succesfully!”, “SQL Information”, MessageBoxButtons.OK, MessageBoxIcon.Information)
    End If
    ‘Closing SQL-connection
    cnConnection.Close()

    ‘Catching SQL-exceptions
Catch sqlEx As SqlException
    MessageBox.Show(sqlEx.Message, “SQL ERROR”, MessageBoxButtons.OK, MessageBoxIcon.Error)

    ‘Catching remaining exceptions
Catch ex As Exception
    MessageBox.Show(ex.Message, “Common Error”, MessageBoxButtons.OK, MessageBoxIcon.Error)

End Try

Leave a Comment