问题
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