1

每次我尝试连接到数据库时,它都会给我这个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
4

3 回答 3

2

你已经实例化了一个OleDbConnection对象,但是你没有设置connectionstring属性,所以它不知道它应该连接到哪里。你也没有打开它。您的代码应类似于:

Dim myConnection As OleDbConnection = New OleDbConnection()
myConnection.ConnectionString = myConnectionString
myConnection.Open()
' execute queries, etc
myConnection.Close()
于 2013-03-23T09:55:38.980 回答
1

您从未将连接字符串分配给连接对象,就像错误所说的那样。

在 con.open 之前插入一行设置连接字符串。

Con.connectionstring = connection Con.Open() 或者更好的是,将您的 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"

使用 Con 作为新的 SqlConnection(connection)

于 2014-11-18T05:27:56.837 回答
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()

这将解决您的问题。如果它不能解决您的问题后回复,我会尝试解决它。

于 2013-06-11T05:40:56.480 回答