我在Visual Studio 2010中创建了Windows应用程序。然后我添加了一个数据库。 数据库属性是:
名称:C:\ USERS \ ADMINISTRATOR \ DOCUMENTS \ VIS STUDIO 2010 \ PROJECTS \ WINDOWSAPPLICATION4 \ WINDOWSAPPLICATION4 \ DATABASE1.MDF
ConnectionString :数据源=。\ SQLEXPRESS; AttachDbFilename =" C:\ Users \ Administrator \ documents \ visual studio 2010 \ Projects \ WindowsApplication4 \ WindowsApplication4 \ Database1.mdf" ; Integrated Security = True; User Instance = True
提供程序:SQL Server的.NET Framework数据提供程序
键入:Microsoft SQL Server
版本:10.00.5500
我写这段代码:
Dim cn As New ADODB.Connection()
cn.Open("provider= SQLOLEDB.1;Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Administrator\documents\visual studio 2010\Projects\WindowsApplication4\WindowsApplication4\Database1.mdf;User Instance=True")
Dim rs As New ADODB.Recordset()
rs.Open(("Select from TB Where Surname = Stylianou "), cn)
While Not rs.EOF
MsgBox("here")
End While
调试器说:无效的连接字符串属性
答案 0 :(得分:4)
几点:
你可以拥有类似的东西:
Imports System.Data.SqlClient
' ...
Private Sub LoadData()
Dim cnsb As New SqlConnectionStringBuilder
cnsb.DataSource = ".\SQLEXPRESS"
cnsb.AttachDBFilename = "C:\Users\Administrator\documents\visual studio 2010\Projects\WindowsApplication4\WindowsApplication4\Database1.mdf"
cnsb.IntegratedSecurity = True
cnsb.UserInstance = True
Using conn As New SqlConnection(cnsb.ConnectionString())
'TODO: Put in the actual column names you want returned
Dim sql As String = "SELECT [Column1], [Column2] FROM [TB] WHERE [Surname] = @Surname"
Using sqlCmd As New SqlCommand(sql, conn)
'TODO: Use the actual .SqlDbType and .Size for the [Surname] column
sqlCmd.Parameters.Add(New SqlParameter With {.ParameterName = "@Surname", .SqlDbType = SqlDbType.NVarChar, .Size = 50, .Value = "Stylianou"})
Dim rdr As SqlDataReader = sqlCmd.ExecuteReader()
While rdr.Read()
' do something with the results
MsgBox(String.Format("Col1={0}, Col2={1}", rdr.GetString(0), rdr.GetString(1)))
End While
End Using
End Using
End Sub
如果那里有任何你想要了解更多的命令(我相信你会这样做;))那么。在Visual Studio中,将光标放在命令名称中,然后按F1。
编辑:您的连接字符串不起作用的原因可能是文件名中有空格。如果查看SqlConnectionStringBuilder提供的值,它会自动用双引号括起文件名。但是,我真的建议使用上面的代码而不是代码。