.NET - 导入与数据库连接的类

时间:2015-05-31 15:44:54

标签: mysql vb.net class connection

我想将一个类导入另一个类,这样我就不必编写相同的代码X次了。

我有一个名为 connectDB.vb 的数据库连接文件。

Imports MySql.Data.MySqlClient

Namespace connectDB1
    Public Class connectDB
        Dim connection As New MySqlConnection("Server=localhost; UserId=root; 
                                Password=root; Database=something")

        Public Sub doConnection()
            Try
                connection.Open()
            Catch ex As Exception
                MsgBox("Error")
            End Try
        End Sub
    End Class
End Namespace

我想将 connectDB.vb 导入 File1.vb

Imports MySql.Data.MySqlClient
Imports MyApp.connectDB1

Public Class File1

    Dim connectDataBase As New connectDB
    Dim connection As New MySqlConnection("Server=localhost; UserId=root; Password=root; Database=something")

    Private Sub File1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'doConnection()
        connectDataBase.doConnexion()
    End Sub

    'Private Sub doConnection()
    '    Try
    '        connection.Open()
    '    Catch ex As Exception
    '        MsgBox("Error")
    '    End Try
    'End Sub

    Private Sub addProduct()
        Dim dbcomm As MySqlCommand
        Dim dbread As MySqlDataReader

        If txtBoxQuantity.Text <> "" And txtBoxPrice.Text <> "" And txtBoxProduct.Text <> "" Then
            dbcomm = New MySqlCommand("insert into products (price, stock, name) values(@price, @stock, @name)", connection)
            dbcomm.Parameters.AddWithValue("@price", txtBoxPrice.Text())
            dbcomm.Parameters.AddWithValue("@stock", txtBoxQuantity.Text())
            dbcomm.Parameters.AddWithValue("@name", txtBoxProduct.Text())
            dbread = dbcomm.ExecuteReader() ' GIVES ERROR
            dbread.Close()
        End If
    End Sub

    Private Sub add_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles agregarProducto.Click
        addProduct()
    End Sub
End Class

但是,当我运行此代码以便将数据保存在数据库中时,它会给我这个错误:

InvalidOperationException未处理。连接必须有效且开放。

connectDB.vb连接到数据库,因为我调试并连接到数据库,但是当我想在File1.vb中执行一些sql语句时,它会给出错误。

在不尝试导入类的情况下,代码可以正常工作,但我只是想改进我的代码,因为您可以看到注释代码是我用来连接数据库的代码。

1 个答案:

答案 0 :(得分:0)

尝试添加此

Public Sub New()
  connectDataBase = New connectDB()
  connection = New MySqlConnection("Server=localhost; UserId=root; Password=root; Database=something")
End Sub