Multiply Insert to MySQL with vb.net - mysql

i have a problem for put in multiply input
Try
Dim StrSQL As String = "INSERT INTO boranga" & _
"(IdBorangA,Answers)" & _
"VALUES (#B_IdA,#B_Answer);"
Dim myCommand As MySqlCommand = New MySqlCommand(StrSQL, conn.open)
myCommand.CommandType = CommandType.Text
Dim parameterB_IdA As MySqlParameter = New MySqlParameter("#B_IdA", MySqlDbType.VarChar, 300)
parameterB_IdA.Value = Label1.Text
Dim parameterB_Answer As MySqlParameter = New MySqlParameter("#B_Answer", MySqlDbType.VarChar, 300)
parameterB_Answer.Value = TextBox1.Text
With myCommand.Parameters
.Add(parameterB_IdA)
.Add(parameterB_Answer)
End With
Dim result As MySqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
MsgBox("Tersimpan", vbYes, "boranga")
Catch SqlEx As MySqlException
Throw New Exception(SqlEx.Message.ToString())
End Try
this current code is for putting only one input for each table "IdBorangA" and "Answer"
i try by tweak it a little bit
Try
Dim StrSQL As String = "INSERT INTO boranga" & _
"(IdBorangA,Answers)" & _
"VALUES (#B_IdA,#B_Answer);"
Dim myCommand As MySqlCommand = New MySqlCommand(StrSQL, conn.open)
myCommand.CommandType = CommandType.Text
Dim parameterB_IdA As MySqlParameter = New MySqlParameter("#B_IdA", MySqlDbType.VarChar, 300)
parameterB_IdA.Value = Label1.Text
parameterB_IdA.Value = Label2.Text
Dim parameterB_Answer As MySqlParameter = New MySqlParameter("#B_Answer", MySqlDbType.VarChar, 300)
parameterB_Answer.Value = TextBox1.Text
parameterB_Answer.Value = TextBox2.Text
With myCommand.Parameters
.Add(parameterB_IdA)
.Add(parameterB_Answer)
End With
Dim result As MySqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)
MsgBox("Tersimpan", vbYes, "boranga")
Catch SqlEx As MySqlException
Throw New Exception(SqlEx.Message.ToString())
End Try
by adding more parameter "parameterB_IdA.Value = Label1.Text" for IdBorangA
and "parameterB_Answer.Value = TextBox2.Text" for Answer
but the result i get that the table only filling with the data from Label2.text and Textbox2.text.
i dunno what went wrong..
if you guys have any idea to help me about this problem.
feel free to answer :)

This line is wrong
Dim myCommand As MySqlCommand = New MySqlCommand(StrSQL, conn.open)
the correct one is
Dim myCommand As MySqlCommand = New MySqlCommand(StrSQL, conn)
This query is an INSERT so you need to call ExecuteNonQuery not ExecuteReader which is intended for data retrivial with a MySqlDataReader
And, of course, you write only one record in the database not two, you are only changing the value of the parameters before sending the command to the database, only the last value will be written.

Related

checkboxlist selected items not gets select & inserts blank values in string

I have a form in which data gets insert. There are some checkboxlist. CheckboxList binds with table in db. Now after selecting items it should enter selected values in db table but it inserts empty strings.
I have two checkboxlist (products, payment) Payment works fine. problem is in products.
VB code
Private Sub list_business_hospital_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.PopulateProducts()
Me.PopulatePayments()
End Sub
Private Sub PopulateProducts()
productsList.Items.Clear()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "select * from chemistsProducts"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("productName").ToString()
item.Value = sdr("productName").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
productsList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
productsList.Items.Insert(0, New ListItem("All", "All"))
End Sub
Private Sub PopulatePayments()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "select * from payment"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("paymentName").ToString()
item.Value = sdr("paymentID").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
ListPayment.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
ListPayment.Items.Insert(0, New ListItem("All", "All"))
End Sub
Private Sub save_Click(sender As Object, e As EventArgs) Handles save.Click
Dim selectedProducts As String = String.Empty
For Each chk As ListItem In productsList.Items
If chk.Selected = True Then
selectedProducts &= "<li>" + chk.Text + "</li>"
End If
Next
Dim payments As String = String.Empty
For Each chk As ListItem In ListPayment.Items
If chk.Selected = True Then
payments &= "<li>" + chk.Text + "</li>"
End If
Next
Try
Dim str1 As String = "INSERT INTO chemists (`products`, `payment`) values ('" + selectedProducts + "', '" + payments + "')"
Dim str2 As MySqlDataReader
Dim adapter As New MySqlDataAdapter
Dim command As New MySqlCommand
command.CommandText = str1
command.Connection = con
adapter.SelectCommand = command
con.Open()
str2 = command.ExecuteReader
con.Close()
Response.Redirect("business-added.aspx")
Catch ex As Exception
Response.Write(ex)
End Try
End Sub
Here Payment gets inserted what I have selected. Problem is in selectedProducts
Try below in page load,
If Not IsPostBack Then
Me.PopulateProducts()
Me.PopulatePayments()
End If

Multiple tables using dataReader

I'm trying to load data into text field from two table in mysql database, but it won't load
Here is my code
Private Sub LoadData()
connString = "Server=Localhost;Database=smart_parking;User Id=root;password="
conn = New MySqlConnection(connString)
conn.Open()
sql = "select a.*, k.* from a anggota, k kendaraan where a.id_card = '" + ComboId.Text + "'"
Dim SqlCommand As New MySqlCommand(sql, conn)
reader = SqlCommand.ExecuteReader
Try
reader.Read()
TxtKartu.Text = reader.GetString(0)
TxtId.Text = reader.GetString(1)
TxtNama.Text = reader.GetString(2)
TxtAlamat.Text = reader.GetString(3)
TxtUmur.Text = reader.GetString(4)
TxtPekerjaan.Text = reader.GetString(5)
Catch ex As Exception
MsgBox(ex)
End Try
conn.Close()
End Sub
it didn't say anything, just can't load any data to the text field. But if I use only one table, it worked perfectly.
Anyone know what the problem is ? Thanks in advance

No Load DataGridView from mysql BBDD vb.net

I want to show a table of my database, after this code worked but now does not work and i dont know because it doesn't work...
when load this form I don't see any table... sorry a I need help...
Where do can be wrong?
Imports MySql.Data.MySqlClient
Public Class inicio
Dim MysqlConn As MySqlConnection
Dim myCommand As New MySqlCommand
Dim updatecommand As New MySqlCommand
Dim deletecommand As New MySqlCommand
Dim myAdapter As New MySqlDataAdapter
Dim myData As New DataTable
Dim SQL As String
Private Sub inicio_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MysqlConn = New MySqlConnection()
' Define the SQL to grab data from table.
SQL = "SELECT * FROM compras"
'Connection String
MysqlConn.ConnectionString = "server=localhost;" _
& "user id=root;" _
& "password=;" _
& "database=comerciojuegos"
' Try, Catch, Finally
Try
MysqlConn.Open()
myCommand.Connection = MysqlConn
myCommand.CommandText = SQL
myAdapter.SelectCommand = myCommand
myAdapter.Fill(myData)
DataGridView1.DataSource = myData
'updatecommand = New MySqlCommand("update compras set id_compra=#id_compra,id_comprador=#id_comprador,id_producto=#id_producto,fecha_compra=#fecha_compra,detalles_compra=#detalles_compra where (id_compra=#id_compra)", MysqlConn)
'updatecommand.Parameters.Add("#id_compra", MySqlDbType.Int16, 50, "id_compra")
'updatecommand.Parameters.Add("#id_comprador", MySqlDbType.Int16, 50, "id_comprador")
'updatecommand.Parameters.Add("#id_producto", MySqlDbType.Int16, 50, "id_producto")
'updatecommand.Parameters.Add("#fecha_compra", MySqlDbType.Date, 50, "fecha_compra")
'updatecommand.Parameters.Add("#detalles_compra", MySqlDbType.VarChar, 50, "detalles_compra")
'myAdapter.UpdateCommand = updatecommand
DataGridView1.Refresh()
Catch myerror As MySqlException
MessageBox.Show("Cannot connect to database: " & myerror.Message)
Finally
MysqlConn.Close()
MysqlConn.Dispose()
End Try
End Sub

What is wrong in this code Vb MySql data to TextBox

What is wrong in this code
I run the software click the button and nothing happens if you have a better code that would help thanks in advance
Dim sql As String
Dim con As MySqlConnection = New
MySqlConnection("Server=localhost;Database=******;Uid=*****;password =******")
Dim ds As DataSet = New DataSet
Dim dataadapter As MySqlDataAdapter = New MySqlDataAdapter
Dim cmd As MySqlCommand = New MySqlCommand()
Dim datareader As MySqlDataReader
Try
sql = "SELECT * FROM users"
con.Open()
cmd.CommandText = sql
cmd.Connection = con
dataadapter.SelectCommand = cmd
datareader = cmd.ExecuteReader
While datareader.Read
datareader.Read()
Email.Text = datareader("Email")
LastName.Text = datareader("LastName")
Address.Text = datareader("Address")
End While
Catch ex As Exception
End Try
con.Close()
End Sub
Narrow the scope of your select. The way its written I think it might set the textbox 100 times if 100 results are returned. Here is how I would write this:
Imports MySql.Data.MySqlClient
Public Sub getData()
Dim objConn As MySqlConnection = New MySqlConnection("Data Source=localhost;" _
& "Database=TestDB;" _
& "User ID=Root;" _
& "Password=myPassword;")
Dim strSQL As String = "SELECT TOP 1 Email, LastName, Address FROM users"
Dim da As MySql.Data.MySqlClient.MySqlDataAdapter
Dim dt As New DataTable
Try
objConn.Open()
da = New MySql.Data.MySqlClient.MySqlDataAdapter(strSQL, objConn)
da.Fill(dt)
If dt.Rows.Count > 0 Then
Email.Text = dt.Rows(0)("Email").ToString
LastName.Text = dt.Rows(0)("LastName").ToString
Address.Text = dt.Rows(0)("Address").ToString
End If
da = Nothing
objConn.Close()
objConn = Nothing
Catch ex As Exception
objConn.Close()
objConn = Nothing
End Try
End Sub

VB MySql AddWithValue doesn't pass the value successfully

I have the following VB code
Dim cmd As New MySqlCommand("SELECT code FROM decoder WHERE ann_id = #aid", conn)
cmd.Parameters.AddWithValue("#aid", 1)
Dim reader As MySqlDataReader = cmd.ExecuteReader()
The reader.Read() then gives me nothing, however, if I replace the code by
Dim cmd As New MySqlCommand("SELECT code FROM decoder WHERE ann_id = 1", conn)
Dim reader As MySqlDataReader = cmd.ExecuteReader()
reader.Read() gives the correct result. Tried using Add instead, doesn't help. What am I missing here?
Many thanks,
remove #
Dim cmd As New MySqlCommand("SELECT code FROM decoder WHERE ann_id = #aid", conn)
cmd.Parameters.AddWithValue("aid", 1)
Dim reader As MySqlDataReader = cmd.ExecuteReader()
Private Sub ButtonInsert_Click(sender As Object, e As EventArgs) Handles ButtonInsert.Click
Dim conn As New MySqlConnection
Dim cmd As New MySqlCommand
conn.ConnectionString = Me.Tag.ToString
Try
conn.Open()
cmd.Connection = conn
cmd.CommandText = "INSERT INTO myTable VALUES(NULL, #number, #text)"
cmd.Prepare()
cmd.Parameters.AddWithValue("#number", 1) 'sets #number to be numeric
cmd.Parameters.AddWithValue("#text", "One") 'sets #text to be characters
For i = 1 To 1000
cmd.Parameters("#number").Value = i
cmd.Parameters("#text").Value = "A string value"
cmd.ExecuteNonQuery()
Next
Catch ex As MySqlException
MessageBox.Show("Error " & ex.Number & " has occurred: " & ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try