【问题标题】:ExecuteScalar Error when Creating Custom ID创建自定义 ID 时执行标量错误
【发布时间】:2014-04-02 02:02:00
【问题描述】:

我目前在创建自定义 ID 时面临 executeScalar 问题。错误是

用户代码未处理 InvalidOperationException。

Message=连接必须有效且打开。

下面是我的代码:

Dim str As String = "select isnull(max(idcr_record),0)+1 from cr_record where Emplid = '" & Session("Emplid") & "'"
Dim com As New MySqlCommand()
'this line was the error
'
Dim count As Integer = Convert.ToInt32(com.ExecuteScalar())

If count = 1 Then
    'insert if no record found
    '
    Dim cc As New MySqlCommand("insert into cr_record values (" & count & "," & Session("Emplid") & ")")
    cc.ExecuteNonQuery()
Else
    'update becoz record already exist
    '
    Dim upd As String = "update cr_record set idcr_record = " & count & " where Emplid = " & Session("Emplid") & " "
    Dim cc As New MySqlCommand(upd)
    cc.ExecuteNonQuery()
End If

Dim length As Integer = 0
Dim val As String = Convert.ToString(count)
length = val.Length
If length = 1 Then
    val = "CR " + "00000" & Convert.ToString(count)
End If
If length = 2 Then
    val = "CR " + "0000" & Convert.ToString(count)
End If
If length = 3 Then
    val = "CR " + "000" & Convert.ToString(count)
End If
If length = 4 Then
    val = "CR " + "00" & Convert.ToString(count)
End If
If length = 5 Then
    val = "CR " + "0" & Convert.ToString(count)
End If
cr_id = "" & val

【问题讨论】:

  • 你在哪里打开你的连接?即 Dim con as new MySqlConnection(connectionstringvariable)
  • @attila owh 我还必须再次打开连接..因为当它开始运行时我已经打开连接..我会尝试你的建议 tq
  • @attila 我只是建立一个开放连接它仍然面临同样的错误..

标签: mysql vb.net executenonquery


【解决方案1】:

至少,您需要将您的 SQL 命令字符串和SqlConnection 对象传递给SqlCommand 对象,然后才能执行命令:

Dim str As String = "select isnull(max(idcr_record),0)+1 from cr_record where Emplid = '" & Session("Emplid") & "'"
Dim conn As New MySqlConnection
conn.ConnectionString = "....."

'pass your SQL command string and MySqlConnection object to MySqlCommand
'
Dim com As New MySqlCommand(str, conn)

conn.Open()
Dim count As Integer = Convert.ToInt32(com.ExecuteScalar())

【讨论】:

    猜你喜欢
    • 2016-08-03
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多