2014-01-06 115 views
0

我已经继承了要维护的软件。以前的版本使用第三方Datagridview替代品,它与Vista中的Windows版本不兼容。在试图将Datagridviews放入时,我遇到了连接到数据库的问题。打开SQL连接

我想制作一个小程序,在原始软件之外连接和选择,以便我可以进一步了解我在做什么,而无需通过使用原始软件进行测试的全过程点。

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设置”,该计划的其余部分的形式加载,进口,和DataGridView的格式。我不认为它会影响SQL部分,并且在这里包含会很麻烦。

这会导致看起来是封闭的连接。

![连接属性] http://i.imgur.com/b5V3Qy5.png

这是我的SQLExpress截图可能帮助诊断连接问题。

![SQL属性] 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

你需要填充数据表 – Ric

+0

前打开连接我接着说:con.Open()'和我仍然得到同样的例外只有更快。 – ZL1Corvette

+1

从MSDN - > _如果Fill方法发现连接尚未打开,则隐式地打开DataAdapter正在使用的Connection。如果填充打开了连接,填充完成后它也将关闭连接._ – Steve

回答

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 
+0

我仍然收到“尝试附加自动命名...”错误。这是说附加,好像我试图创建一个数据库或表,实际上我试图打开一个。还是我读了太多的错误? – ZL1Corvette

+1

添加'con.Open()'后发现错字!谢谢。 – ZL1Corvette