每次我尝试连接数据库时,都会给我error "The ConnectionString property has not been initialized"
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
答案 0 :(得分:2)
您已实例化OleDbConnection
对象,但尚未设置connectionstring
属性,因此它不知道应该连接到何处。你还没有打开它。您的代码应该类似于:
Dim myConnection As OleDbConnection = New OleDbConnection()
myConnection.ConnectionString = myConnectionString
myConnection.Open()
' execute queries, etc
myConnection.Close()
答案 1 :(得分:1)
此问题在您不考虑建立新连接时发生 解决方案非常简单,您所要做的就是制作
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()
这将解决您的问题。 如果它没有解决你的问题,我会尝试解决它。
答案 2 :(得分:1)
您从未将连接字符串分配给连接对象,就像错误所说的那样。
在con.open之前插入设置连接字符串的行。
Con.connectionstring =连接 Con.Open() 或者更好的是,更改您的使用声明如下
Dim Connection As String =“Data Source =。\ SQLEXPRESS; AttachDbFilename = G:\ VB Project \ Library Catalog System \ Library Catalog System \ library.mdf; Integrated 安全性=真;连接超时= 30;用户实例=真“
使用Con As New SqlConnection(连接)