database VB.NET 中的“ConnectionString 属性尚未初始化”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9162647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"The ConnectionString property has not been initialized" error in VB.NET
提问by CompleteNewb
Every time I tried to connect to the database it give me this error "The ConnectionString property has not been initialized"
每次我尝试连接到数据库时,它都会给我这个错误“ConnectionString 属性尚未初始化”
what can I do to solve this?
我能做些什么来解决这个问题?
here are my codes
这是我的代码
Module Module1
Function GetInfoForStudent(ByRef QueryName As String, ByVal UserName As String, ByVal Password As String) As DataTable
Using Con As New SqlConnection
Try
Using OleCon As New SqlConnection
Dim Connection As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=G:\VB Project\Library
Catalog System\Library Catalog System\library.mdf;Integrated
Security=True;Connect Timeout=30;User Instance=True"
Con.Open()
Dim Cmd As SqlCommand = Con.CreateCommand()
Cmd.CommandType = CommandType.StoredProcedure
Cmd.CommandText = QueryName
Cmd.Parameters.AddWithValue("@user", UserName)
Cmd.Parameters.AddWithValue("@pass", Password)
Dim da As New SqlDataAdapter(Cmd)
Dim ds As New DataTable()
da.Fill(ds)
Return ds
End Using
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Using
End Function
End Module
Sub ShowStudentInfo()
Dim dt As DataTable = GetInfoForStudent("MyStoredProcName", "@user", "@pass")
' Since (presumably) only one is returned
With dt.Rows(0)
' Assign your text boxes
StudentIDTextBox.Text = .Item("StudentID")
LoginIDTextBox.Text = .Item("LoginID")
Student_NameTextBox.Text = .Item("Student Name")
Student_addressTextBox.Text = .Item("Student address")
End With
End Sub
回答by JohnFx
You never assigned your connection string to the connection object, just like the error is saying.
您从未将连接字符串分配给连接对象,就像错误所说的那样。
Insert a line setting the connection string before con.open.
在 con.open 之前插入一行设置连接字符串。
Con.connectionstring = connection
Con.Open()
Or better yet, change your using statement as follows
或者更好的是,更改您的 using 语句如下
Dim Connection As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=G:\VB Project\Library Catalog System\Library Catalog System\library.mdf;Integrated
Security=True;Connect Timeout=30;User Instance=True"
Using Con As New SqlConnection(connection)
回答by bschultz
You are creating the connection string object but never assigning it to your SqlCommandobject.
您正在创建连接字符串对象,但从未将其分配给您的SqlCommand对象。

