VB-SQL,SELECT语句中的异常

时间:2012-03-03 09:32:14

标签: mysql visual-studio-2008

导入System.Data.SqlClient

Public Class Form3

Private cs As New SqlConnection("Data Source=HUSAIN-PC;Initial 

Catalog = final1; Integrated Security = True“)

Private da As New SqlDataAdapter
Private ds As New DataSet
Public dr As SqlDataReader
Public cmd As New SqlCommand
Private sql As String
Private sqlsel As String
Dim Bal As String
Dim id As String
Dim amt As String

Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    cs.Open()
    cmd.Connection = cs
    amt = TextBox2.Text
    id = TextBox1.Text
    sqlsel = "SELECT (Bal) FROM db5 WHERE Id='" + id + "'"
    da.InsertCommand = New SqlCommand(sqlsel, cs)
    dr = cmd.ExecuteReader
    If dr.HasRows = True Then
        While (dr.Read())
            Bal = dr("Id")
        End While
    End If
    dr.Close()
    MessageBox.Show("Balance is :" + Bal)

    Dim total As String = Bal + amt

    sql = "UPDATE db5 SET Bal='" + total + "' WHERE Id='" + id + "'"
    da.InsertCommand = New SqlCommand(sql, cs)
    da.InsertCommand.ExecuteNonQuery()
    MessageBox.Show("updated")
End Sub

结束班

这是我从VB DB中检索值的VB代码... Update语句正常运行bt我写了select我在代码中得到一个异常: DR = cmd.ExecuteReader “ExecuteReader:CommandText属性尚未初始化”

1 个答案:

答案 0 :(得分:0)

看看这段代码:

sqlsel = "SELECT (Bal) FROM db5 WHERE Id='" + id + "'"
da.InsertCommand = New SqlCommand(sqlsel, cs)
dr = cmd.ExecuteReader

您将InsertCommand指定为SELECT查询,但是您在一个完全独立的ExecuteReader上调用SqlDataReader ...但未配置查询,根据错误消息。

这就是您收到此特定错误的原因,但此代码存在很多问题:

  • 每次要执行查询时,您应该创建新的SqlConnection / SqlCommand
  • 您应该使用Using语句自动关闭它们
  • 你不应该有实例变量 - 它们应该是局部变量
  • 我认为没有理由在这里使用DataAdapter - 只需使用SqlCommand.ExecuteNonQuery
  • 非常重要:您应该使用参数化SQL,而不是直接在SQL中包含值。有关此主题的详细信息,请参阅Bobby Tables网站。