2012-02-06 46 views
3

每次我試圖連接到數據庫,它給我這個錯誤「ConnectionString屬性尚未初始化」在VB.NET

我能做些什麼來解決「ConnectionString屬性尚未初始化」錯誤這個?

這裏是我的代碼

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 

回答

5

您從未將連接字符串分配給連接對象,就像錯誤所述。

在con.open之前插入一條設置連接字符串的行。

Con.connectionstring = connection 
Con.Open() 

或者更好的是,如下

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

謝謝你改變你使用的語句!現在正在工作。 – CompleteNewb 2012-02-06 15:53:38

+0

您可能還會看看「OleCon」代碼,因爲您從不使用該變量,所以似乎沒有必要。順便說一句:所有的感謝,我需要的是upvote。 – JohnFx 2012-02-06 16:09:55

+0

好的,我改變了陳述,並再次感謝。儘管我想給你點贊,但我仍然缺乏聲譽。但我非常感謝你的幫助,祝你有美好的一天。 – CompleteNewb 2012-02-06 16:21:05

1

您所創建的連接字符串對象,但從來沒有將其分配給您的SqlCommand對象。