Failed to insert data - mysql

I'm trying to add data to a MySQL Server database.
Here is the code:
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As SqlConnection = New SqlConnection("Data Source=192.168.3.173\hidp;Initial Catalog=HIDP;Persist Security Info=True;User ID=intranet;Password=kikapu;APP=Intranet")
Dim sql As String = "Insert into [RAVARIAS].[StockMovimentos] ([CodHospital], [utilizador], [servico], [CodDevice], [CodConsumivel], [TipoMovimento], [DtMovimento], [Qtd]) values (#CodHospital, #utilizador, #servico, #CodDevice, #CodConsumivel, #TipoMovimento, #DtMovimento, #Qtd)"
Dim cmd As SqlCommand = New SqlCommand(sql, connection)
cmd.Parameters.AddWithValue("#CodHospital", Session("Codhospital"))
cmd.Parameters.AddWithValue("#utilizador", TextBox1.Text)
cmd.Parameters.AddWithValue("#servico", TextBox2.Text)
cmd.Parameters.AddWithValue("#CodDevice", DropDownList3.SelectedItem)
cmd.Parameters.AddWithValue("#CodConsumivel", DropDownList4.SelectedItem)
cmd.Parameters.AddWithValue("#TipoMovimento", DropDownList2.SelectedItem)
cmd.Parameters.AddWithValue("#DtMovimento", Calendar1.SelectedDate)
cmd.Parameters.AddWithValue("#Qtd", TextBox4.Text)
connection.Open()
cmd.ExecuteNonQuery()
connection.Close()
TextBox1.Text = ""
TextBox2.Text = ""
TextBox4.Text = ""
DropDownList2.ClearSelection()
DropDownList3.ClearSelection()
DropDownList4.ClearSelection()
Calendar1.SelectedDates.Clear()
End Sub
When I click on the button nothing happens.

Related

Vb.net Mysql Multiple queries in one data

I'm trying to make a chat in Vb.net using MySQL and I want to load the chat into a list-box where would be the (username) ''par'' and the (message).
But it keeps showing me errors and i don't understand how to solve it.
Here's my code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim stringConn As String
Dim stringCmd As String
Dim myConn As MySqlConnection
Dim myCmd As MySqlCommand
stringCmd = "SELECT par, message FROM chat"
stringConn = "server=localhost; user id=studio; password=mypw; database=studio;"
myConn = New MySqlConnection(stringConn)
myCmd = New MySqlCommand(stringCmd, myConn)
myConn.Open()
Dim myReader As MySqlDataReader
myReader = myCmd.ExecuteReader()
'Reset your List box here.
ListBox1.Items.Clear()
While myReader.Read()
--------------Here is my problem ---------------
ListBox1.Items.Add(myReader.GetString(1//username//) & " " & myReader.GetString(2//message//))
----end-- of the---problem---
End While
myReader.Close()
myConn.Close()
End Sub
You could try this:
If myReader.HasRows = True Then
Do While myReader.Read()
ListBox1.Items.Add(myReader(0) & " " & myReader(1))
Loop
End If
Best Regards

Object reference isn't set to an instance of an object

The error is in this image:
How do I fix this?
My code:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim con As New MySqlConnection("host=localhost; username=root; database= login")
Dim cmd As MySqlCommand
Dim dr As MySqlDataReader
con.Open()
cmd.Connection = con 'this is where I have an error
cmd.CommandText = "select userID, password from login where userID= ' " & userIDtxt.Text & " ' and password = ' " & pwTxt.Text & " '"
dr = cmd.ExecuteReader
If dr.HasRows Then
MsgBox("Login successful!")
Me.Hide()
MainForm.Show()
Else
MsgBox("Username or password does not match")
userIDtxt.Text = ""
pwTxt.Text = " "
End If
End Sub
End Class
your sql connection string missing true credentials, this sample to connect to mysql with vb and c#:
https://dev.mysql.com/doc/connector-net/en/connector-net-programming-connecting-open.html
You haven't initialized a new instance of your cmd variable.
Change:
Dim cmd As MySqlCommand
to:
Dim cmd As New MySqlCommand

VB.NET: can't read database records with MySQL Data Reader dr.HasRows

when i click the button 2 with the valid ID No. on the text box it always shows the message box "Invalid ID No." but if i remove the IF statement, it shows database records and it works fine, but i need this IF statement, i think the problem here is the dr.HasRows but i don't know what to put.
Imports MySql.Data.MySqlClient
Public Class Form16
Private Sub Form16_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim con As New MySqlConnection("server=localhost;user id=root;password=root;database=db")
Dim DataSet1 As New DataSet
Dim dr As MySqlDataReader
Dim da As New MySqlDataAdapter
Dim cmd As New MySqlCommand
con.ConnectionString = "server = localhost; user id = root;password=root; database = db"
cmd.Connection = con
con.Open()
cmd.CommandText = "select * from voter where idn='" & TextBox1.Text & "'"
dr = cmd.ExecuteReader
con.Close()
da.SelectCommand = cmd
da.Fill(DataSet1, "db")
If dr.HasRows Then
Label2.DataBindings.Add("text", DataSet1, "db.fname")
Label10.DataBindings.Add("text", DataSet1, "db.mi")
Label11.DataBindings.Add("text", DataSet1, "db.lname")
Label12.DataBindings.Add("text", DataSet1, "db.yr")
Label13.DataBindings.Add("text", DataSet1, "db.sec")
Label14.DataBindings.Add("text", DataSet1, "db.vstatus")
Else
MessageBox.Show("Invalid ID No.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Label2.DataBindings.Clear()
Label10.DataBindings.Clear()
Label11.DataBindings.Clear()
Label12.DataBindings.Clear()
Label13.DataBindings.Clear()
Label14.DataBindings.Clear()
End Sub
End Class
You need to use Parameterized query to prevent SQL Injection
Dim commandText as String = "SELECT * FROM Voter WHERE idn=#idn"
Dim command As New MySqlCommand(commandText, connection)
command.Parameters.AddWithValue("#idn", TextBox1.Text)
You don't need to use DataSet and DataAdapter if you are using a DataReader because you could convert your DataReader to a DataTable:
dr = command.ExecuteReader() ' Get Data Reader Rows
dt.Load(dr) 'Convert DataReader into DataTable
Which now could be bind to your Label or TextBox:
Label2.DataBindings.Add("Text", dt, "fname")
You don't need then to use HasRows property to check if DataReader has rows, instead you could check the Row Count of your DataTable:
If (dt.Rows.Count > 0) Then
Label2.DataBindings.Add("Text", dt, "fname")
End If
I am also using the Using statement in dotNet specially for connection so that you don't have to close:
Using connection As New MySqlConnection(connectionString)
'More code here
End Using ' Close the connection automatically
Check Complete Code Below:
Imports MySql.Data.MySqlClient
Public Class Form16
Dim connectionString as String = "server = localhost; user id = root;password=root; database = db"
Dim dt as DataTable
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Using connection As New MySqlConnection(connectionString)
' Use Parameterized query
Dim commandText as String = "SELECT * FROM Voter WHERE idn=#idn"
Dim command As New MySqlCommand(commandText, connection)
Dim dr As MySqlDataReader
' Add idn value using parameterized query
command.Parameters.AddWithValue("#idn", TextBox1.Text)
Try
connection.Open() ' Open Connection
dr = command.ExecuteReader()
dt = New DataTable()
dt.Load(dr)
If (dt.Rows.Count > 0) Then
Label2.DataBindings.Add("Text", dt, "fname")
Label10.DataBindings.Add("Text", dt, "mi")
Label11.DataBindings.Add("Text", dt, "lname")
Label12.DataBindings.Add("Text", dt, "yr")
Label13.DataBindings.Add("Text", dt, "sec")
Label14.DataBindings.Add("Text", dt, "vstatus")
Else
MessageBox.Show("Invalid ID No.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Using
End Sub
End Class
You have done more work than you have to...if you are going to use a datareader, your code should end up looking something like this. (I have not tested this code)
Imports MySql.Data.MySqlClient
Public Class Form16
Private Sub Form16_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim con As New MySqlConnection("server=localhost;user id=root;password=root;database=db")
Dim DataSet1 As New DataSet
Dim dr As MySqlDataReader
Dim da As New MySqlDataAdapter
Dim cmd As New MySqlCommand
con.ConnectionString = "server = localhost; user id = root;password=root; database = db"
cmd.Connection = con
con.Open()
cmd.CommandText = "select * from voter where idn='" & TextBox1.Text & "'"
dr = cmd.ExecuteReader
con.Close()
if dr.read then
Label2.text = dr("fname")
Label10.text = dr("mi")
Label11.text = dr("lname")
Label12.text = dr("yr")
Label13.text = dr("sec")
Label14.text = dr("vstatus")
else
MessageBox.show("Invalid ID Number")
endif
End Class

how to write update code vb.net and sql geeks

I wrote this update code for mysql server using vb.net and its not working.
Dim sqlstring = "Update initial_nom set f_name = '" &
TextBox1.Text & "',s_name = '" &
TextBox2.Text & "',th_name = '" &
TextBox3.Text & "',fo_name = '" &
TextBox4 & "',adm_type = '" &
ComboBox4.SelectedItem.ToString() & "'
where (app_no = " & TextBox5.Text & ")"
cmd.ExecuteNonQuery()
Try this:
Dim connectionString As String = "Server=my_server;Database=my_db;Uid=my_username;Pwd=my_password;"
Dim SQLConnection As New MySqlConnection(connectionString)
Dim SQLCommand As New MySqlCommand()
With SQLCommand
.CommandText = "UPDATE initial_nom SET f_name = #f_name, s_name = #s_name, th_name = #th_name, fo_name = #fo_name, adm_type = #adm_type WHERE app_no = #app_no"
.Connection = SQLConnection
.Parameters.AddWithValue("#f_name", TextBox1.Text)
.Parameters.AddWithValue("#s_name", TextBox2.Text)
.Parameters.AddWithValue("#th_name", TextBox3.Text)
.Parameters.AddWithValue("#fo_name", TextBox4.Text)
.Parameters.AddWithValue("#app_no", TextBox5.Text)
.Parameters.AddWithValue("#adm_type", ComboBox4.SelectedItem.ToString)
End With
Try
SQLConnection.Open()
SQLCommand.ExecuteNonQuery()
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
Finally
SQLConnection.Close()
End Try
Don't forget to enter your own details in the connection string.
In answer to your other closed question, this should do what you want:
Dim connectionString As String = "Server=my_server;Database=my_db;Uid=my_username;Pwd=my_password;"
Dim SQLConnection As New MySqlConnection(connectionString)
Dim SQLCommand As New MySqlCommand()
With SQLCommand
.CommandText = "INSERT INTO nomination (f_name, s_name, th_name, fo_name, app_no, adm_type) values (#f_name, #s_name, #th_name, #fo_name, #app_no, #adm_type)"
.Connection = SQLConnection
.Parameters.AddWithValue("#f_name", TextBox1.Text)
.Parameters.AddWithValue("#s_name", TextBox2.Text)
.Parameters.AddWithValue("#th_name", TextBox3.Text)
.Parameters.AddWithValue("#fo_name", TextBox4.Text)
.Parameters.AddWithValue("#app_no", TextBox5.Text)
.Parameters.AddWithValue("#adm_type", ComboBox4.SelectedItem.ToString)
End With
Try
SQLConnection.Open()
SQLCommand.ExecuteNonQuery()
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
Finally
SQLConnection.Close()
End Try
Update
I noticed in your other question that you were struggling with ADODB and a connection DSN, there is a far easier way to do this using the MySQL Connector.
Download and install the MySQL Connector from http://dev.mysql.com/downloads/connector/net/
You now need to add a reference to this in your project:
Select Browse and navigate to the Assemblies directory for the MySQL Connector:
Select MySQL.Data.dll and click Ok:
Now all you need to do is add Imports MySql.Data.MySqlClient to the very top of your form code and you will be able to access your database once you have created the correct connection string.
Here is some example code which will give you and idea of how you can perform some simple operations on your DB, this is tested and working (I was bored this morning!).
Imports MySql.Data.MySqlClient
Public Class Form1
Dim connectionString As String = "Server=my_server;Database=my_db;Uid=my_username;Pwd=my_password;"
Dim SQLConnection As New MySqlConnection(connectionString)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For i As Integer = 0 To 5
ComboBox4.Items.Add(i)
Next
ComboBox4.SelectedIndex = 0
End Sub
Private Sub update_row()
Dim SQLCommand As New MySqlCommand()
With SQLCommand
.CommandText = "UPDATE nomination SET f_name = #f_name, s_name = #s_name, th_name = #th_name, fo_name = #fo_name, adm_type = #adm_type WHERE app_no = #app_no"
.Connection = SQLConnection
.Parameters.AddWithValue("#f_name", TextBox1.Text)
.Parameters.AddWithValue("#s_name", TextBox2.Text)
.Parameters.AddWithValue("#th_name", TextBox3.Text)
.Parameters.AddWithValue("#fo_name", TextBox4.Text)
.Parameters.AddWithValue("#app_no", TextBox5.Text)
.Parameters.AddWithValue("#adm_type", ComboBox4.SelectedItem.ToString)
End With
Try
SQLConnection.Open()
SQLCommand.ExecuteNonQuery()
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
Finally
SQLConnection.Close()
End Try
End Sub
Private Sub insert_row()
Dim SQLCommand As New MySqlCommand()
With SQLCommand
.CommandText = "INSERT INTO nomination (f_name, s_name, th_name, fo_name, app_no, adm_type) values (#f_name, #s_name, #th_name, #fo_name, #app_no, #adm_type)"
.Connection = SQLConnection
.Parameters.AddWithValue("#f_name", TextBox1.Text)
.Parameters.AddWithValue("#s_name", TextBox2.Text)
.Parameters.AddWithValue("#th_name", TextBox3.Text)
.Parameters.AddWithValue("#fo_name", TextBox4.Text)
.Parameters.AddWithValue("#app_no", TextBox5.Text)
.Parameters.AddWithValue("#adm_type", ComboBox4.SelectedItem.ToString)
End With
Try
SQLConnection.Open()
SQLCommand.ExecuteNonQuery()
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
Finally
SQLConnection.Close()
End Try
End Sub
Private Sub select_from()
Dim SQLCommand As New MySqlCommand
Dim SQLAdapter As New MySqlDataAdapter
Dim DTable As New DataTable
With SQLCommand
.CommandText = "SELECT * FROM nomination"
.Connection = SQLConnection
End With
Try
SQLConnection.Open()
SQLAdapter.SelectCommand = SQLCommand
SQLAdapter.Fill(DTable)
DataGridView1.DataSource = DTable
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
Finally
SQLConnection.Close()
End Try
End Sub
Private Sub create_table()
Dim SQLCommand As New MySqlCommand
With SQLCommand
.CommandText = "CREATE TABLE nomination (f_name varchar(50),s_name varchar(50),th_name varchar(50),fo_name varchar(50),app_no varchar(50),adm_type varchar(50))"
.Connection = SQLConnection
End With
Try
SQLConnection.Open()
SQLCommand.ExecuteNonQuery()
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
Finally
SQLConnection.Close()
End Try
End Sub
Private Sub drop_table()
If MsgBox("Are you really sure you want to DROP this table?", MsgBoxStyle.Question + MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
Dim SQLCommand As New MySqlCommand
With SQLCommand
.CommandText = "DROP TABLE nomination"
.Connection = SQLConnection
End With
Try
SQLConnection.Open()
SQLCommand.ExecuteNonQuery()
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
Finally
SQLConnection.Close()
End Try
End If
End Sub
Private Sub truncate_table()
If MsgBox("Are you really sure you want to TRUNCATE this table?", MsgBoxStyle.Question + MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
Dim SQLCommand As New MySqlCommand
With SQLCommand
.CommandText = "TRUNCATE TABLE nomination"
.Connection = SQLConnection
End With
Try
SQLConnection.Open()
SQLCommand.ExecuteNonQuery()
Catch ex As MySqlException
MsgBox(ex.Message.ToString)
Finally
SQLConnection.Close()
End Try
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
create_table()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
drop_table()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
insert_row()
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
update_row()
End Sub
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
select_from()
End Sub
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
truncate_table()
End Sub
End Class
Here's the form I used, it needs Button1 - Button6, TextBox1 - TextBox5, ComboBox4 and a DataGridView control.
Hope this helps you out.

Update SQL statement in vb.net

I am new in VB.NET and as well as SQL. I want to update records in my database. I made a dummy in my database.
Example the values are: ID = 1, name=Cath, age=21
In my interface made in VB.NET, I update the values example : name = txtName.Text and age = txtAge.Text where ID = 1. This is in my main form. In my main form, I have "view" button informing that by clicking that button, new form would pop up and would view the updated values by the user. The program does not have any errors except that when I want to update again the values in my SQL, It record BUT when I click "view" button again, It will show the previous inputted by the user (the first update upon running the interface). What should be the solution?
This is my code:
Mainform:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SQLConnection.ConnectionString = ServerString
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
MessageBox.Show("Successful connection")
Else
'SQLConnection.Close()
MessageBox.Show("Connection is closed")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Sub SaveNames(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
MsgBox("Successfully Added!")
End Sub
Private Sub cmdSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSave.Click
Dim date_now As String
date_now = Format(dtpDate.Value, "yyyy-MM-dd")
Dim SQLStatement As String = "UPDATE people SET name='" & txtName.Text & "', date ='" & date_now & "' WHERE 1"
SaveNames(SQLStatement)
End Sub
Form 2: (where the updated data would be viewed)
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SQLConnection.ConnectionString = ServerString
Try
If SQLConnection.State = ConnectionState.Closed Then
SQLConnection.Open()
'====retrieve / update values in database=============
Dim SQLStatement As String = "SELECT name, date FROM people"
ViewInfos(SQLStatement)
Else
'SQLConnection.Close()
MessageBox.Show("Connection is closed")
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Sub ViewInfos(ByRef SQLStatement As String)
Dim cmd As MySqlCommand = New MySqlCommand
With cmd
.CommandText = SQLStatement
.CommandType = CommandType.Text
.Connection = SQLConnection
.ExecuteNonQuery()
End With
'--read the records in database in phpmyadmin gui---
Dim myReader As MySqlDataReader = cmd.ExecuteReader
If myReader.Read Then
lblName.Text = myReader.GetString(0)
lblDate.Text = myReader.GetString(1)
End If
myReader.Close()
MsgBox("Records Successfully Retrieved")
End Sub
Any help would be appreciated. Thanks!
You are leaving your connection string open when you update sql, thus when you try to retrieve the data, your condition closes the connection without reading the data or updating your textboxes.
Take out the .ExecuteNonQuery() from the ViewInfos() method.
Refer to your forms via variables not via the form name:
Dim myForm as New Form2()
myForm.Show()