这是关于按钮事件点击功能的代码
Dim con As New Koneksi
DataGridView1.Rows.Add(con.getIdTambahBarang(cbBarang.Text), _
con.getNamaTambahBarang(cbBarang.Text), _
con.getHargaTambahBarang(cbBarang.Text), _
txtJumlah.Text)
这是我的类Koneksi代码:
Public Function getIdNamaHargaTambahBarang(ByVal namaBarang As String, ByVal params As String) As String
Dim id As String = ""
Dim nama As String = ""
Dim harga As String = ""
Try
bukaKoneksi()
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = "SELECT * FROM barang WHERE nama_barang like '" & namaBarang & "'"
reader = cmd.ExecuteReader
If (reader.Read()) Then
If params = "getNama" Then
nama = reader.GetString(1)
Return nama
End If
If params = "getHarga" Then
harga = reader.GetDouble(2).ToString
Return harga
End If
If params = "getId" Then
id = reader.GetString(0)
Return id
End If
End If
tutupKoneksi()
Catch ex As Exception
End Try
End Function
Public Function getIdTambahBarang(ByVal namaBarang As String) As String
Return getIdNamaHargaTambahBarang(namaBarang, "getId")
End Function
Public Function getNamaTambahBarang(ByVal namaBarang As String) As String
Return getIdNamaHargaTambahBarang(namaBarang, "getNama")
End Function
Public Function getHargaTambahBarang(ByVal namaBarang As String) As String
Return getIdNamaHargaTambahBarang(namaBarang, "getHarga")
End Function
上面的两个代码都产生了
System.Data.dll错误中发生'System.InvalidOperationException'。
当我调试它时,con的第二次调用产生了这个错误。看来在VB.NET中,实例类函数一次只能调用一次,任何解决方案?
答案 0 :(得分:1)
考虑重构代码。你实际上是在3次点击数据库,每次都有一个LIKE
子句,你真的只需要这样做一次。
建议这样的事情,它只执行一次对数据库的调用,执行与您相同的业务逻辑。它也有一些SQL注入预防。
Dim con As New Koneksi
Dim barang As Barang = Koneksi.GetBarang()
DataGridView1.Rows.Add(barang.id,
barang.nama, _
barang.harga, _
txtJumlah.Text)
Public Class Koneksi
Public Function GetBarang(nama_barang As String)
Dim barang As New Barang
bukaKoneksi()
cmd.Connection = con
cmd.CommandType = CommandType.Text
cmd.CommandText = "SELECT id,name,harga FROM barang WHERE nama_barang = @nama"
cmd.Parameters.AddWithValue("@nama", namaBarang)
reader = cmd.ExecuteReader
If (reader.Read()) Then
barang.id = reader.reader.GetString(0)
barang.nama = reader.GetString(1)
barang.harga = reader.GetDouble(2).ToString
End If
tutupKoneksi()
Return barang
End Function
End Class
barang
个对象属性。所有三个属性都是从DB一次收集的。当您不可避免地想要向DataGridView添加另一个属性时,您不必再对数据库进行任何额外的往返,而只需修改您的SQL语句和.Rows.Add
)调用。LIKE
子句,您实际上只需要= name
,因此数据库以前使用了更多资源。