Could not insert the data using vb.net into Mysql - mysql

I am trying to insert data into MySQL using VB.
When I use these textboxes to insert the data the data gets added, but I don't want to enter the text into textboxes but directly add the underlying information just by press of button (update). It is giving a syntax error to check MySQL version. It it a query error? I don't know how to do this. Please help. Here is my code.
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Mysqlconn = New MySqlConnection
Mysqlconn.ConnectionString = "server=localhost;userid=root;port=85;password=*****;database=data"
Dim reader As MySqlDataReader
Try
Mysqlconn.Open()
Dim query As String
query = "INSERT INTO 'data'.'etable'('eid','Name','Surname','Age')values('7','Andy','Roddick','35')"
command = New MySqlCommand(query, Mysqlconn)
reader = command.ExecuteReader
MessageBox.Show("Data Saved")
Mysqlconn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Mysqlconn.Dispose()
End Try
End Sub
End Class

Try this, which fixes some other issues and potential issues as well:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim query As String = "INSERT INTO `data`.`etable`(eid,Name,Surname,Age)" & _
" VALUES (#eid, #Name, #Surname, #Age)"
Using con As New MySqlConnection("server=localhost;userid=DONT_USE_ROOT!;port=85;password=*****;database=data"), _
cmd As New MySqlCommand(query, con)
'Guessing at parameter types/lengths here.
cmd.Parameters.Add("#eid", MySqlDbType.Int32).Value = 7
cmd.Parameters.Add("#Name", MySqlDbType.VarChar, 20).Value = "Andy"
cmd.Parameters.Add("#Surname", MySqlDbType.VarChar, 25).Value = "Roddick"
cmd.Parameters.Add("#Age", MySqlDbType.Int32).Value = 35
conn.Open()
If cmd.ExecuteNonQuery() > 0 Then MessageBox.Show("Data Saved")
End Using
End Sub
Notice I also removed the exception handler. The Dispose() call in your old handler is now no longer needed (the Using block takes care of this), and I tend to advocate handling exceptions at a higher level than where they are thrown... though in this case you're already in the button event. What I really recommend here is moving the database code to it's own class, so this would all be in a separate method in that class. Then you could still have your exception handler here in the button click event, and the only thing in the Try block would be calling that method.
It's also very important to be in the habit of using query parameters for data that goes into sql queries, in order to prevent sql injection attacks. What you had wasn't vulnerable to attack yet, but it didn't lend any confidence that it wouldn't be vulnerable soon.

The correct character to enclose table name and field names is the backtick not the single quote. Use ALT+096 on your numeric keypad to insert it.
query = "INSERT INTO `data`.`etable`(`eid`,`Name`,`Surname`,`Age`) " & _
"values('7','Andy','Roddick','35')"
Said that, check if you database table has the field eid and Age of type varchar. If the fields are numeric (as the name seems to imply) then your query should be changed to
query = "INSERT INTO `data`.`etable`(`eid`,`Name`,`Surname`,`Age`) " & _
"values(7,'Andy','Roddick',35)"
You code also contains some bad practice that need to be removed to avoid future problems
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim query As String
query = "INSERT INTO `data`.`etable`(`eid`,`Name`,`Surname`,`Age`) " & _
"values(7,'Andy','Roddick',35)"
Using Mysqlconn = New MySqlConnection
Using command = New MySqlCommand(query, Mysqlconn)
Mysqlconn.ConnectionString = "server=localhost;userid=root;port=85;password=*****;database=data"
Try
Mysqlconn.Open()
Dim rowsAffected = command.ExecuteNonQuery()
if rowsAffected > 0 Then
MessageBox.Show("Data Saved")
End If
Catch ex As MySqlException
MessageBox.Show(ex.Message)
End Try
End Using
End Using
End Sub
First enclose all disposable objects in a Using statement to be sure that they are closed and disposed also in case of exceptions then do not use ExecuteReader for INSERT, UPDATE and DELETE queries, instead the correct method to use is ExecuteNonQuery

Related

Trying to enter records into a mysql database using vb.net but its not working and I cant figure out why

Mysql is connected to my vb so thats not the problem Im not really sure whats wrong.
This is a register account form, im using xampp for mysql.
Public Class Reigsteraccount
Public Class Form1
Dim conn As MySqlConnection
Dim COMMAND As MySqlCommand
Dim WithEvents Button1 As New Button
Dim WithEvents Textbox1 As New TextBox
Dim WithEvents Textbox2 As New TextBox
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
conn = New MySqlConnection
conn.ConnectionString = "server=localhost;userid=root;password=root;database=compproject"
Dim READER As MySqlDataReader
Try
conn.Open()
Dim Query As String
Query = "insert into compproject.users (Usernames,Passwordhash) values ('" & Textbox1.Text & "','" & Textbox2.Text & "')"
COMMAND = New MySqlCommand(Query, conn)
READER = COMMAND.ExecuteReader
MessageBox.Show("Record added")
conn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Dispose()
End Try
End Sub
End Class
First of all, that's some very bad code - I know this isn't CodeReview, but still, it needs to be pointed out! Have a look at codereview.stackexchange.com if you want to brush up on best practices (I appreciate you might be a first time coder...).
To answer the question, you are using COMMAND.ExecuteReader - this should be replaced with COMMAND.ExecuteNonQuery. You're not reading from the database, you're writing data into it (INSERT command in the SQL).
If it still doesn't work after changing that, please update your question to include more detail, such as the exception generated, etc.

I got this error for auto _Suggest and error is "Object reference not set an instance of an object "

Public Sub auto_Suggest(ByVal member As String, ByVal table As String, ByVal txt As Object)
Try
dta = New DataTable
'open the connection
conn.Open()
'holds the data in the database
With cmda
.Connection = conn
.CommandText = "select " & member & " from " & table
End With
'''''''''''''''fill data in the table
daa.SelectCommand = cmda
daa.Fill(dta)
''function of autocomplete
Dim r As DataRow
txt.AutoCompleteCustomSource.Clear()
For Each r In dta.Rows
txt.AutoCompleteCustomSource.Add(r.Item(0).ToString)
Next
''''''''''''''''''''''''
Catch ex As Exception
MsgBox(ex.Message)
End Try
''''close the connection
conn.Close()
daa.Dispose()
End Sub
Private Sub Stock_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
'call a public sub
'the job_id is the field of a table , the employees is the name of a table and a textbox is an object
auto_Suggest("ItemName", "stock", TxtItemName)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
First, it's good to employ a "use it and lose it" approach and take advantage of Using blocks to automatically dispose of connections, commands, and readers. See the example below.
Second, please set a breakpoint on the first line after the Try statement and step through your source in the debugger. If the exception is reached, inspect the ex variable and potentially the ex.InnerException (if any).
Last, the example here uses SQLConnection and SQLCommand (SQL Server). Just swap out whatever library you are using for MySQL and you should be good to go.
Public Sub auto_Suggest(connectionString As String, member As String, table As String, txt As TextBox)
Try
txt.AutoCompleteCustomSource.Clear()
Using cn = New SqlConnection(connectionString)
cn.Open()
Using cmd = New SqlCommand("SELECT " & member & " FROM " & table, cn)
Using dr = cmd.ExecuteReader()
While dr.Read
txt.AutoCompleteCustomSource.Add(dr(member).ToString)
End While
End Using
End Using
End Using
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub

update query not working when i attach the content of text box using data reader on page load

Code works fine when i remove the page load content. this is a form which will allow user to edit the data already present in database. i just want to let a user edit a form which he have already submitted.
This is the code:
Dim con As New SqlConnection("Data Source=ENCODER-PC\SQLEXPRESS;Integrated Security=True")
Dim cmd, com As New SqlCommand
Dim dr As SqlDataReader
Dim n, d, a As Integer
Dim returnValue As Object
Dim str As String
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
str = "select * from School where RollNo=11"
com = New SqlCommand(str, con)
dr = com.ExecuteReader()
con.Open()
If (dr.Read()) Then
Enroll.Text = dr("RollNo").ToString()
Name.Text = dr("Name").ToString()
Class.Text = dr("Class").ToString()
End If
con.Close()
dr.Close()
End Sub
Protected Sub Next_Click(sender As Object, e As EventArgs) Handles [Next].Click
Try
cmd.CommandText = "Update School SET RollNo='" & Enroll.Text & "', Name='" & Name.Text & "', Class='" & Class.Text & "' where RollNo=11 "
cmd.Connection = con
con.Open()
MsgBox("Connection is Open ! ")
n = cmd.ExecuteNonQuery
If n > 0 Then
MsgBox("data inserted successfully")
Else
MsgBox("data insertion failed")
End If
Catch ex As Exception
MsgBox(ex.ToString())
Finally
con.Close()
End Try
End Sub
You have tagged your question with MySql but in code you use the classes for Sql Server and a connection string specific to Sql Server.
So you should clarify this point. However, in the meantime I wish to give an answer to some errors in your Page_Load event handler:
First you need to check if the call to Page_Load is a postback from other controls and avoid to reload the data from the database in that case. See ASP.NET Page Life Cycle
Second, open the connection before executing the reader
Dim constring = "Data Source=ENCODER-PC\SQLEXPRESS;Integrated Security=True"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim str = "select * from School where RollNo=11"
If Not IsPostBack Then
Using con = new SqlConnection(conString)
Using cmd = new SqlCommand(str, con)
con.Open()
Using dr = com.ExecuteReader()
If (dr.Read()) Then
Enroll.Text = dr("RollNo").ToString()
Name.Text = dr("Name").ToString()
Class.Text = dr("Class").ToString()
End If
End Using
End Using
End Using
End If
End Sub
As you can see there are other improvements: No more global variables for connection, command and reader and Using Statement around the disposable objects.
If this code is really intended to run against a MySql database then you need to use the appropriate classes like MySqlConnection, MySqlCommand, MySqlDataReader etc.. and fix the connectionstring

Fatal Error Encounter During Command Execution MySQL VB

ijust finish my code for inserting data using the vb and mySQL but when i run my webpage it seem have an error Fatal Error Encounter During Command Execution . Please help some how to solve it. below is my code.
Imports System.Data.SqlClient
Imports MySql.Data.MySqlClient
Partial Class Request
Inherits System.Web.UI.Page
Dim MessageBox As Object
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
txt1.Focus()
txt2.Focus()
txt3.Focus()
txt4.Focus()
txt5.Focus()
txt6.Focus()
txt7.Focus()
ddl1.Focus()
ddl2.Focus()
ddl3.Focus()
ddl4.Focus()
End Sub
Protected Sub btnsubmit_Click(sender As Object, e As EventArgs) Handles btnsubmit.Click
'Create sql connection and fetch data from database based on employee id
Dim conn As New MySql.Data.MySqlClient.MySqlConnection
Dim strConnectionString As String = ConfigurationManager.ConnectionStrings("testConnectionString").ConnectionString
Try
conn.ConnectionString = strConnectionString
conn.Open()
Catch ex As MySql.Data.MySqlClient.MySqlException
MessageBox.Show(ex.Message)
End Try
' Dim cr_id As String
' cr_id = "CR004"
Dim iReturn As Boolean
Using SQLConnection As New MySqlConnection(strConnectionString)
Using sqlCommand As New MySqlCommand()
sqlCommand.Connection = SQLConnection
With sqlCommand
.CommandText = "INSERT INTO cr_record(idcr_record,Emplid,Nama,date,DeptDesc,email,change,reasonchange,problem,priority,reasondescription,systemrequest) VALUES (#IDCR,#Emplid,#Nama,#date,#DeptDesc,'#email,#change,#reasonchange,#problem,#priority,#reasondescription,#systemrequest)"
' .CommandTimeout = 5000000
.CommandType = Data.CommandType.Text
.Parameters.AddWithValue("#Emplid", txt1.Text)
.Parameters.AddWithValue("#Nama", TextBox1.Text)
.Parameters.AddWithValue("#date", txt5.Text)
.Parameters.AddWithValue("#DeptDesc", txt2.Text)
.Parameters.AddWithValue("#email", txt4.Text)
.Parameters.AddWithValue("#change", ddl2.Text)
.Parameters.AddWithValue("#reasonchange", txt6.Text)
.Parameters.AddWithValue("#problem", ddl3.Text)
.Parameters.AddWithValue("#priority", rbl1.Text)
.Parameters.AddWithValue("#reasondescription", txt7.Text)
.Parameters.AddWithValue("#systemrequest", ddl4.Text)
End With
Try
SQLConnection.Open()
' sqlCommand.ExecuteNonQuery()
sqlCommand.ExecuteNonQuery()
iReturn = True
MsgBox("Added Successfully")
Catch ex As MySqlException
MsgBox(ex.Message.ToString & Err.Description)
iReturn = False
Finally
SQLConnection.Close()
End Try
End Using
End Using
Return
End Sub
End Class
you probably forgot to add this parameter #IDCR
.Parameters.AddWithValue("#IDCR", toyourvariable)
Syntax error in your query:
[...snip...]tDesc,'#email,#change,#rea[...snip...]
^---mis-placed quote.
Reserved words:
[...snip...]c,email,change,reasonc[...snip...]
^^^^^^---- quote with backticks: `change`
Solution that i used and it really works.
This error is mostly caused by a MISSING or Incorrectly Spelled Parameter declaration. eg. #FirstName mistakenly spelled for #FirtName.
Make sure that all the parameters that are declared in the sql query are all declared in the AddwithValue Parameter declaration. (It helps to count the query versus the Addwithvalues).
The best solution is for visual studio to provide information about the missing Parameter. Use a Try-Catch block. In the catch block use Messagebox.show(ex.Innerexception.Message) instead of Messagebox.show(ex.message). This will show the exact Parameter that is missing. eg. below
Try
conCommand.Parameters.Addwithvalue("#FirstName", txtFirstName.text)
conCommand.Parameters.Addwithvalue("#MiddleName", txtMiddleName.text)
conCommand.Parameters.Addwithvalue("#LastName", txtLastName.text)
conCommand.Parameters.Addwithvalue("#PhoneNo", txtPhoneno.text)
catch ex as exception
Messagebox.show(ex.innerexception.Message)
End Try
Hope this helps. Its really great that we share our ideas in the world of programming.

SQL and VISUAL BASIC 2008 Queries

How can I write a sql query that takes information from a database, and then put in the text in a label? I'm not really sure how to do this.
MSDN has lots of examples of getting data via ADO.NET. E.g. http://msdn.microsoft.com/library/dw70f090.
You will need to adjust the connection and command types (and the connection string) to be correct for My SQL. If you have ODBC drivers for My SQL then you can follow the ODBC example with just a change of connection string.
For using MySQL with .NET I'd recommend you this tutorial, and for your problem specially part 6, about reading the data with a MySQLDataReader.
An (almost working) sample by copy&paste from there with some changes:
Private Sub getData()
Dim conn As New MySqlConnection
Dim myCommand As New MySqlCommand
Dim myReader As MySqlDataReader
Dim SQL As String
SQL = "SELECT LabelContent FROM myTable"
conn.ConnectionString = myConnString ' your connection string here'
Try
conn.Open()
Try
myCommand.Connection = conn
myCommand.CommandText = SQL
myReader = myCommand.ExecuteReader
' loop through all records'
While myReader.Read
Dim myLabelValue as String
myLabelValue = myReader.GetString(myReader.GetOrdinal("LabelContent"))
' ... do something with the value, e.g. assign to label '
End While
Catch myerror As MySqlException
MsgBox("There was an error reading from the database: " & myerror.Message)
End Try
Catch myerror As MySqlException
MessageBox.Show("Error connecting to the database: " & myerror.Message)
Finally
If conn.State <> ConnectionState.Closed Then conn.Close()
End Try
End Sub
For selecting one column to label from ms access 2007 database just follow this step
Create ms access database for example i make name "test.accdb" and make 1 column for example column name is "ColumnName" and one table with name "Table1"
save it on whatever folder
open vb 2008 and make one form
import adodb on first writing
write this code inside class
Sub lihat()
Dim str As String = "select * from Table1"
Dim cn As New OleDb.OleDbConnection
Dim com As New OleDb.OleDbCommand
Dim adp As OleDb.OleDbDataReader
With cn
.ConnectionString = "Provider=Microsoft.ace.oledb.12.0;data source=test.accdb;persist security info=false"
.Open()
End With
With com
.Connection = cn
.CommandText = str
End With
adp = com.ExecuteReader
adp.Read()
Label1.Text = adp(1)
cn.Close()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
lihat()
End Sub
number 1 on adp(1) is number of column on Table1.