如何为所有查询仅打开一个数据库连接

时间:2019-05-29 08:34:27

标签: mysql vb.net

问题是: 如果我每100毫秒在计时器中打开一次数据库连接,是否会有任何问题? 我认为最好的方法是打开一次连接,然后在需要的所有时间进行查询。对吧?

我的代码是:

 Friend conexion As MySqlConnection
    Private cmd As New MySqlCommand
    Private dr As MySqlDataReader
    Private ConnectionString = "server=localhost; uid=root; pwd=; database=myblahdb;"

  conexion = New MySqlConnection()
  conexion.ConnectionString = ConnectionString
conexion.Open()

 Dim cmd As New MySqlCommand
       With cmd
            .CommandText = "select blah blah"
            .CommandType = CommandType.Text
            .Connection = conexion
        End With
        dr = cmd.ExecuteReader

        If dr.HasRows Then
            dr.Read()
            //do stuff
        End If

        cmd.Dispose()
        dr.Close()
        dr.Dispose()
        conexion.Close()
        conexion.Dispose()

1 个答案:

答案 0 :(得分:0)

将其移动到form_load以便在开始时执行

conexion = New MySqlConnection()
conexion.ConnectionString = ConnectionString
conexion.Open()

然后在退出时进行

 conexion.Close()
 conexion.Dispose()

是解决方案