Click here to Skip to main content
15,912,205 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to create a database. the database name will be savefiledialog file name. And it will create on selected directory of savefiledialog. (i have added a savefiledialog on my form). Following code creating database in MSSQL default folder. Help plz

VB
Private Sub Button14_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button14.Click

        Dim filename, dbPath As String

        SaveFileDialog1.Filter = "MS SQL Database File (*.mdf*)|*.mdf"
        If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            dbPath = SaveFileDialog1.FileName
            filename = System.IO.Path.GetFileNameWithoutExtension(dbPath)
            Dim str As String
            Dim myConn = New SqlConnection("Data Source=.\SQLEXPRESS;Integrated security=true;database=")

            str = "CREATE DATABASE " + filename + ";"
            Dim myCommand = New SqlCommand(str, myConn)
            Try
                myConn.Open()
                myCommand.ExecuteNonQuery()
                MessageBox.Show("DataBase is Created Successfully", "New Database", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Catch ex As Exception
                MessageBox.Show(ex.ToString(), "New Database", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Finally
                If (myConn.State = ConnectionState.Open) Then
                    myConn.Close()
                End If
            End Try
        End If

    End Sub
Posted

1 solution

Dim str As String

Dim myConn As SqlConnection = New SqlConnection("Server=(local)\netsdk;" & _
"uid=sa;pwd=;database=master")

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)

Try
myConn.Open()
myCommand.ExecuteNonQuery()
MessageBox.Show("Database is created successfully", _
"MyProgram", MessageBoxButtons.OK, _
MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show(ex.ToString())
Finally
If (myConn.State = ConnectionState.Open) Then
myConn.Close()
End If
End Try
 
Share this answer
 
Comments
Member 10457175 11-Dec-13 9:11am    
Your code will create a database named MyDatabaseData.mdf in D:\MyFolder directory. But i want to create a database with file name typed in savefiledialog and in savefildialog directory.

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900