2013-03-23 189 views
0

每次我試圖連接到數據庫,它給我這個error "The ConnectionString property has not been initialized"「ConnectionString屬性尚未初始化」的錯誤在VB.NET

How can i avoid this error and make it work?

這裏是我的代碼:

Imports System.Data.OleDb 
Public Class frmLoginPage 
Dim con As New OleDbConnection 
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
    Dim dt As New DataTable 
    Dim ds As New DataSet 
    ds.Tables.Add(dt) 
    Dim da As New OleDbDataAdapter 

    da = New OleDbDataAdapter("Select*from tblPassword", con) 
    da.Fill(dt) 

    Dim newRow As DataRow = dt.NewRow 
    With newRow 
     If .Item("Username") = txtUsername.Text And .Item("Password") = txtPassword.Text Then frmMainMenu.ShowDialog() Else MsgBox("The username or password you entered was incorrect, please try again!", MsgBoxStyle.Critical, "Information") 
    End With 
End Sub 

回答

2

您已經實例化了一個OleDbConnection對象,但您尚未設置connectionstring屬性,因此它不知道它應該連接到的位置。你還沒有打開它。您的代碼應該是這個樣子:

Dim myConnection As OleDbConnection = New OleDbConnection() 
myConnection.ConnectionString = myConnectionString 
myConnection.Open() 
' execute queries, etc 
myConnection.Close() 
+0

你能告訴我在哪裏把它寫在我的編碼中,以及如何使它合適,還有一點點帽子說「myconnectionString」,它說「'myconnectionString'沒有聲明。它可能無法訪問,因爲它的保護級別「,這是什麼意思? – user2201924

+1

你已經有了你的代碼的第一行,其餘的可以放到你的'Button1_Click'方法中(只需將'myConnection'重命名爲'con')。 'myConnectionString'只是你的真正連接字符串的佔位符,對於SQL Server來說,這將是類似於「」服務器= myServerName \ myInstanceName;數據庫= myDataBase;用戶ID = myUsername;密碼= myPassword;「 – DeanOC

+0

@ user2201924這個解決你的問題嗎?如果你需要更多的幫助,請問:) – DeanOC

0

這個問題,當你DONOT考慮制定一個新的連接發生 的解決方案很簡單,所有你需要做的就是讓

Dim conString as string = "Your connection string here" 

Dim con As new OleDbConnection 
con.connectionSting= ConSting 
con.open() 
     'now simply write the query you want to be executed 


'At the end write 
con.close() 

這將解決你的問題。 如果它不能解決您的問題發佈回覆我會盡力解決它。

1

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

在con.open之前插入一條設置連接字符串的行。 \ VB項目:AttachDbFilename = G;

Con.connectionstring =連接 Con.Open() 或者更好的是,如下

昏暗連接的String =「數據源= \ SQLEXPRESS改變你使用的語句\圖書館目錄系統\圖書館目錄系統\爲Library.mdf;集成 安全= TRUE;連接超時= 30;用戶實例=真」

使用精讀作爲新的SqlConnection(連接)

相關問題