How to drop database and delete .mdf file using vb.net

  • Hi Guys,

    I have code in vb.net that checks if my database exists. If it doesn't I run a script to create it. but if it already exists and say I want to give a user the option to create the db from scratch I need to drop the database as well as delete the mdf file.

    Reason being I created an installer with my application. and while testing the user installed the software and it created the database. but then we found issues with the installer.

    so now when I re-install I removed sql server but the mdf file for my database wasn't deleted from the sql server data folder, since the files where there the script bombed out saying the file already exists.

    how can I bypass this error??

  • Dim SQLString As String = _

    "IF EXISTS (" & _

    "SELECT * " & _

    "FROM master..sysdatabases " & _

    "WHERE Name = '" & newDatabaseName.Text & "')" & vbCrLf & _

    "DROP DATABASE " & newDatabaseName.Text & ""

    Try

    Dim SQLConnection As New SqlClient.SqlConnection

    SQLConnection.ConnectionString = SQLConnectionString

    Dim Command As New SqlClient.SqlCommand(SQLString, SQLConnection)

    SQLConnection.Open()

    Command.ExecuteNonQuery()

    SQLConnection.Close()

    Catch ex As Exception

    MessageBox.Show(ex.Message)

    End Try

  •  

    Do you have a code like this, may it help you tell me if this one is working fine.

    Dim SQLString As String = _

    "IF EXISTS (" & _

    "SELECT * " & _

    "FROM master..sysdatabases " & _

    "WHERE Name = '" & newDatabaseName.Text & "')" & vbCrLf & _

    "DROP DATABASE " & newDatabaseName.Text & ""

    Try

    Dim SQLConnection As New SqlClient.SqlConnection

    SQLConnection.ConnectionString = SQLConnectionString

    Dim Command As New SqlClient.SqlCommand(SQLString, SQLConnection)

    SQLConnection.Open()

    Command.ExecuteNonQuery()

    SQLConnection.Close()

    Catch ex As Exception

    MessageBox.Show(ex.Message)

    End Try

Viewing 3 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic. Login to reply