使用VB连接数据库时出错 [英] Error at connection to database using VB

查看:152
本文介绍了使用VB连接数据库时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码和/或连接需要帮助。我收到的错误是:



系统类型的未处理异常。 System.Data.dll中发生InvalidOperationException



附加信息:ExecuteReader需要一个开放且可用的连接。连接的当前状态已关闭。




在此代码中:(第4行)



I need help on my codes and/or connection.I'm getting an error that says:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll

Additional information: ExecuteReader requires an open and available Connection. The connection's current state is closed.


In this code:(Line 4)

cmd.Connection = cn
        cmd.CommandText = "SELECT ID, LastName, FirstName FROM tblMembers WHERE ID = @ID"
        cmd.Parameters.Add(New SqlClient.SqlParameter("@ID", SqlDbType.Int)).Value = dg1.Item(0, e.RowIndex).Value
        dr = cmd.ExecuteReader
        If dr.HasRows() Then
            With dr
                .Read()
                txtLname.Text = dr("LastName")
                txtFname.Text = dr("FirstName")
            End With
        End If





但是如果我尝试打开连接。发生这种情况。



System.Data.dll中出现未处理的System.InvalidOperationException类型异常



附加信息:连接未关闭。连接的当前状态是打开的。




使用以下代码:(第1行)





But if I try to open the connection. This happens.

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll

Additional information: The connection was not closed. The connection's current state is open.


With this code:(Line 1)

cn.Open()
        cmd.Connection = cn
        cmd.CommandText = "SELECT ID, LastName, FirstName FROM tblMembers WHERE ID = @ID"
        cmd.Parameters.Add(New SqlClient.SqlParameter("@ID", SqlDbType.Int)).Value = dg1.Item(0, e.RowIndex).Value
        dr = cmd.ExecuteReader
        If dr.HasRows() Then
            With dr
                .Read()
                txtLname.Text = dr("LastName")
                txtFname.Text = dr("FirstName")
            End With
        End If





我尝试了什么:



我尝试运行调试而不用打开连接,它说我需要在第4行打开连接(Executereader),但是如果我打开连接,它说连接没有关闭。



What I have tried:

I tried to run the debug without opening the connection and it says I need to open the connection at line 4 (Executereader) but if I open the connection, it says that the connection was not closed.

推荐答案

信息不足。我猜你在其他地方有代码打开连接但从不关闭它。



所有连接对象都应该在你完成后创建和处理它。一个非常简单的方法是使用语句:

Not enough information. I'm going to guess that you have code elsewhere that opens a connection but never closes it.

All connection objects should be created and disposed when you're finished with it. A very simple way of doing that is the using statement:
using (var conn = new SqlConnection(...))
{
    ... your command and query code goes here ...
}


我怀疑这里有问题:

I suspect a problem here:
cn.Open()
cmd.Connection = cn



但是因为我们有不知道那些对象是什么,不可能给出明确的答案。


But since we have no idea of what are those objects, it impossible to give a definitive answer.


这篇关于使用VB连接数据库时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆