我继承了要维护的软件。之前的版本使用的第三方Datagridview替代品与Vista上的Windows版本不兼容。在尝试放入Datagridviews时,我遇到了连接数据库的问题。
我正在尝试制作一个小程序来解决原始软件之外的连接和SELECT问题,这样我就可以进一步了解我在做什么,而无需完成使用原始软件到达测试点的整个过程
Private Shared Function GetData(ByVal sqlCommand As String) As DataTable
Dim table As New DataTable()
Dim connectionString As String = "Data Source=.\SQLExpress;Integrated Security=true;" _
& "AttachDbFilename=C:blah\blah\blah.mdf;User Instance=true;"
Using con = New SqlConnection(connectionString)
Using command = New SqlCommand(sqlCommand, con)
Using da = New SqlDataAdapter(command)
da.Fill(table)
End Using
End Using
End Using
Return table
End Function
我的SQL命令是一个简单的“Select * FROM Setup”,程序的其余部分是表单加载,导入和DataGridView格式。我不认为它会影响SQL部分,并且包含在这里会很麻烦。
这会导致看似闭合的连接。
![连接属性] http://i.imgur.com/b5V3Qy5.png
这是我的SQLExpress的屏幕截图,可能有助于诊断连接问题。
![SQL Properties] http://i.imgur.com/bakBq5D.png
我用灰色模糊了计算机名称,但我注意到还有另一个粉红色的计算机名称。我不知道这意味着什么,可能这个数据库最初是在另一台计算机上创建的,并且已被复制和粘贴。
最后,这是原始软件使用的连接字符串:
"Data Source=.\SQLExpress;AttachDbFilename=C:\blah\blah\blah.mdf;Trust_Connection=Yes;"
我也尝试过:
"Data Source=.\SQLExpress;AttachDbFilename=C:\blah\blah\blah.mdf;Trusted_Connection=Yes;User Instance=true"
最后,这是我的例外:
"An attempt to attach an auto-named database for file C:\blah\blah\blah.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share."
我从www.connectionstrings.com获得了备用连接字符串。
答案 0 :(得分:0)
您缺少Open()
命令。
con.Open()
完整的代码清单。 (另一个好主意是将代码包装在Try.... End Try
块中)。
Private Shared Function GetData(ByVal sqlCommand As String) As DataTable
Dim table As New DataTable()
Dim connectionString As String = "Data Source=.\SQLExpress;Integrated Security=true;" _
& "AttachDbFilename=C:blah\blah\blah.mdf;User Instance=true;"
Using con = New SqlConnection(connectionString)
conn.Open()
Using command = New SqlCommand(sqlCommand, con)
Using da = New SqlDataAdapter(command)
da.Fill(table)
End Using
End Using
End Using
Return table
End Function