An attempt to attach an auto-named database for fi

2020-05-07 06:03发布

问题:

I am Trying to connect database for first time , and I am getting this error :

An attempt to attach an auto-named database for file VBTestDB.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.

and getting error on

myconnect.Open()

Heres my code :

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim myconnect As New SqlClient.SqlConnection
    myconnect.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=VBTestDB.mdf;Integrated Security=True;User Instance=True;"


    Dim mycommand As SqlClient.SqlCommand = New SqlClient.SqlCommand()
    mycommand.Connection = myconnect
    mycommand.CommandText = "INSERT INTO Card (CardNo,Name) VALUES (@cardno,@name)"
    myconnect.Open()

    Try
        mycommand.Parameters.Add("@cardno", SqlDbType.Int).Value = TextBox1.Text
        mycommand.Parameters.Add("@name", SqlDbType.NVarChar).Value = TextBox2.Text

        mycommand.ExecuteNonQuery()
        MsgBox("Success")
    Catch ex As System.Data.SqlClient.SqlException
        MsgBox(ex.Message)
    End Try
    myconnect.Close()
End Sub

回答1:

I am able to solve my problem. I just change my connection string to :

myconnect.ConnectionString = "Data Source=.\SQLEXPRESS;Initial Catalog=VBTestDB;Integrated Security=True;User Id=sa;Password=welcome1"

and it works fine.

Thanks