0

I have a problem with the following piece of code:

dim nama as string    
cnn.ConnectionString = "Server=localhost; user id=root; password=; database=aplikasi_store_testing;"
        cmd.Connection = cnn
        cnn.Open()
        cmd.CommandText = "SELECT ID_Barang, Nama_Barang from data_barang WHERE ID_Barang= '" & txtIDBarangInput.Text & "';"

Afterwards, I would need to change the data from "Nama_Barang" to nama. Could anyone help me with this? In advance, thank you very much for your precious help!

Vinra Gunanta Pandia
  • 301
  • 7
  • 10
  • 20

2 Answers2

3

Probably you need to execute your command

dim nama as string    
cnn.ConnectionString = "............"
cmd.Connection = cnn
cnn.Open()
cmd.CommandText = "SELECT ID_Barang, Nama_Barang from data_barang WHERE ID_Barang= @id"
cmd.Parameters.AddWithValue("@id", txtIDBarangInput.Text )
Dim reader  = cmd.ExecuteReader()
while reader.Read()
   nama = reader(1).ToString()
End While

Of course this code assumes that you have already declared the connection and the command object.
Note also that I have removed your string concatenation and placed a parameter placeholder.
This is the right thing to do when you build strings to pass to the database engine.
Read about this subject (Sql Injection)

By the way, selecting back the value of ID_Barang that you already know is useless.
Also, on this field, I have a doubt. In your question code you put the value between single quotes treating the value as a string. But the name ID_Barang suggest a numeric value. Are you sure that this field is a text?

Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286
0
cmd.CommandText = "SELECT Nama_Barang from data_barang WHERE ID_Barang = '" & txtIDBarangInput.Text & "';"

Dim o As Object = cmd.ExecuteScalar()

If (Not o.Equals(DBNull.Value)) Then
    nama = DirectCast(o, string)
Else
    name = string.Empty
End If

You should use parameters rather than inserting the id value directly into the query string to avoid sql injection vulnerabilities etc.

gareththegeek
  • 2,362
  • 22
  • 34