An attempt to attach an auto-named database for file failed in Vb.Net

泪湿孤枕 提交于 2019-12-04 07:00:16

问题


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



来源:https://stackoverflow.com/questions/19558415/an-attempt-to-attach-an-auto-named-database-for-file-failed-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!