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!

0

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.