inserting data on mysql using vb.net with VS2010 - mysql

im trying to insert data in mysql but i just cant do it ive tried to search for answers on the net and tried everything on my code but it just wont insert here is the image of the error
hope some one can help me and thanks in advance ... MERRY CHRISTMAS !!
here is the code
myconn = New MySqlConnection
myconn.ConnectionString = "host=127.0.0.1;user=root;password=;database=engr_log"
Dim Reader As MySqlDataReader
Try
myconn.Open()
Dim query As String
query = "insert into log_tbl ('ID', 'owner_name', 'business_name', 'Amount_paid', 'Location', 'Date') values (NULL, '" & txtname.Text & "','" & txtbus.Text & "','" & txtamount.Text & "', '" & txtloc.Text & "','" & dtp1.Value & "');"
command = New MySqlCommand(query, myconn)
Reader = command.ExecuteReader
MessageBox.Show("Entry Saved!!","SAVE", MessageBoxButtons.OK, MessageBoxIcon.Information)
myconn.Close()
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
getlist()
End Sub

Remove the single quotes around the column in your insert statment:
insert into log_tbl (ID, owner_name, business_name, Amount_paid, Location, Date)...
But the bigger problem is you should use queries with parameters to not only avoid errors but also SQL injections.
Example:
Dim connectionString = "host=127.0.0.1;user=root;password=;database=engr_log"
Dim query = "insert into log_tbl (owner_name, business_name, Amount_paid, Location, Date) values (#owner_name, #business_name, #Amount_paid, #Location, #Date);"
Using connection As New MySqlConnection(connectionString)
Dim command As New MySqlCommand(query, connection)
command.Parameters.AddWithValue("#owner_name", txtname.Text)
command.Parameters.AddWithValue("#business_name", txtbus.Text)
command.Parameters.AddWithValue("#Amount_paid", txtamount.Text)
command.Parameters.AddWithValue("#Location", txtloc.Text)
command.Parameters.AddWithValue("#Date", dtp1.Text)
command.Connection.Open()
command.ExecuteNonQuery()
End Using
Even better, you can be explicit with the types:
command.Parameters.Add("#owner_name", SqlDbType.VarChar)
command.Parameters.Add("#business_name", SqlDbType.VarChar)
command.Parameters.Add("#Amount_paid", SqlDbType.Float)
command.Parameters.Add("#Location", SqlDbType.VarChar)
command.Parameters.Add("#Date", SqlDbType.DateTime)

Related

when I add a datetimepicker in visual studio and add the following part of code for the save button using vb.net, why does it show an error message?

Error message - ('Incorrect date value: '11/17/2021' for column 'Date_joined' at row1)
Dim query As String
conn.Open()
query = "INSERT INTO `librarydb`.`tblmember` (`Name`, `NIC`, `Gender`,`Contact`,`Email`,`Date_Joined`) VALUES ('" & txtname.Text & "', '" & txtNIC.Text & "', '" & txtgender.Text & "','" & txtcontact.Text & "','" & txtemail.Text & "','" & DateTimePicker1.Value.Date & "');"
COMMAND = New MySqlCommand(query, conn)
RENDER = Command.ExecuteReader
Never concatenate strings to build a CommandText. ALWAYS use parameters. A value inserted in a text box and concatenated into CommandText can be executed by the server. (Drop Table) Values of parameters are not considered as executable code by the server.
You wouldn't open the connection until directly before the Execute....
You would use ExecuteReader with an Insert command.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim query = "INSERT INTO `librarydb`.`tblmember` (`Name`, `NIC`, `Gender`,`Contact`,`Email`,`Date_Joined`)
VALUES (#Name, #NIC, #Gender, #Contact, #Email, #Date);"
Using conn As New MySqlConnection("Your connection string"),
cmd As New MySqlCommand(query, conn)
With cmd.Parameters
.Add("#Name", MySqlDbType.VarChar).Value = txtname.Text
.Add("#NIC", MySqlDbType.VarChar).Value = txtNIC.Text
.Add("#Gender", MySqlDbType.VarChar).Value = txtgender.Text
.Add("#Contact", MySqlDbType.VarChar).Value = txtcontact.Text
.Add("#Email", MySqlDbType.VarChar).Value = txtemail.Text
.Add("#Date", MySqlDbType.Date).Value = DateTimePicker1.Value.Date
End With
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub

MySQL Query Browser Error Data truncated for column

This is my code and I dont know why I'm getting this Error in my visual studio 2013 and my data base is MySQL Query Browser:
"Additional information: ERROR [HY000] [MySQL][ODBC 3.51 Driver][mysqld-5.1.34-community]Data truncated for column 'userid' at row 1"
If a = "New" Then
Dim sqlstring As String
sqlstring = "INSERT into users(username, userid, usertype, remarks)values('" & TextBox1.Text & "','" & TextBox2.Text & "','" & ComboBox1.Text & "','" & TextBox4.Text & "')"
cmd = New Odbc.OdbcCommand(sqlstring, cnn)
cmd.ExecuteNonQuery()
reset()
disable()
btn3()
End If
This is because the total length of the characters you are passing exceeded the length defined by column userid. Aside from that, mysql has its own managed provider called MySqlClient and this is the one you should be using.
A much better way to good practice programming is to paramaterized your query. Example below is at least your good starting point:
Dim connectionString As String = "..your connection string here..."
Using SQLConnection As New MySqlConnection(connectionString)
Using sqlCommand As New MySqlCommand()
sqlCommand.CommandText = "INSERT into users(username, userid, usertype, remarks) VALUES (#username, #userid, #usertype, #remarks)"
sqlCommand.Connection = SQLConnection
sqlCommand.CommandType = CommandType.Text
sqlCommand.Parameters.AddWithValue("#username", TextBox1.Text)
sqlCommand.Parameters.AddWithValue("#userid", TextBox2.Text)
sqlCommand.Parameters.AddWithValue("#usertype", ComboBox1.Text)
sqlCommand.Parameters.AddWithValue("#remarks", TextBox4.Text)
SQLConnection.Open()
sqlCommand.ExecuteNonQuery()
End Using
End Using

cannot insert path file address to mysql using vb.net

i have problem to insert this text to mysql in vb.net
C:\Users\Riski\Documents\Visual Studio 2012\Projects\Remainder\Remainder\images\activ\
and this my source for insert
Try
Dim tbimg As String
tbimg = tbimgpath.text
'Prepare Connection and Query
dbconn = New MySqlConnection("Server=localhost;Database=team;Uid=root;Pwd=")
'OPEN THE DB AND KICKOFF THE QUERY
dbconn.Open()
DS = New DataSet
DA = New MySqlDataAdapter("INSERT INTO tb_team_user (id_team_user,user_ip,user_team,user_image_path) values (null,'" & lip.Text & "','" & tbteam.Text & "','" & tbimg & "')", dbconn)
DA.Fill(DS, "tb_info_activity")
'DONE CLOSE THE DB
dbconn.Close()
Application.Restart()
Catch ex As Exception
MsgBox("cannot connect to database!" & vbCrLf & vbCrLf & ex.Message)
End Try
if i write without symbol '\' and ':' the insert work fine but if i write with symbol and the insert give me warning just "check the manual that corresponds"
how resolve this?
thanks
Don't use string concatenation to build your sql query. Otherwise you are open for sql injection and other issues like this. The backslash introduces escape characters like \r for carriage return. So just use sql-parameters with the correct types:
Using dbconn = New MySqlConnection("connectionstring")
Dim insertSql = "INSERT INTO tb_team_user (id_team_user,user_ip,user_team,user_image_path)" & _
"VALUES (null,#user_ip,#user_team,#user_image_path)"
Using da As New MySqlDataAdapter()
da.InsertCommand = New MySqlCommand(insertSql, dbconn)
da.InsertCommand.Parameters.Add("#user_ip", MySqlDbType.Int32).Value = Int32.Parse(lip.Text)
da.InsertCommand.Parameters.Add("#user_team", MySqlDbType.VarChar).Value = tbteam.Text
da.InsertCommand.Parameters.Add("#user_image_path", MySqlDbType.VarChar).Value = tbimg.Text
' .. '
End Using
End Using
Apart from that, why do you use an INSERT-sql for DataAdaper.Fill? You need a Select.
So maybe you want to use MySqlCommand.ExecuteNonQuery instead:
Using dbconn = New MySqlConnection("connectionstring")
Dim insertSql = "INSERT INTO tb_team_user (id_team_user,user_ip,user_team,user_image_path)" & _
"VALUES (null,#user_ip,#user_team,#user_image_path)"
Using cmd As New MySqlCommand(insertSql, dbconn)
cmd.Parameters.Add("#user_ip", MySqlDbType.Int32).Value = Int32.Parse(lip.Text)
cmd.Parameters.Add("#user_team", MySqlDbType.VarChar).Value = tbteam.Text
cmd.Parameters.Add("#user_image_path", MySqlDbType.VarChar).Value = tbimg.Text
dbconn.Open()
Dim insertedCount As Int32 = cmd.ExecuteNonQuery()
End Using
End Using

Insert in MySql database DataGrid Values

I want to add to mysql database values which i entered in datagrid view.
To delete currently selected ID i use this code.
Dim reader As MySqlDataReader
Try
SqlConn.Open()
Dim query As String
query = "delete from where id='" & DataGridView1.CurrentRow.Index & "'"
Dim command As New MySqlCommand
command = New MySqlCommand(query, SqlConn)
reader = command.ExecuteReader
MessageBox.Show("Data deleted")
ucitaj()
SqlConn.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
SqlConn.Dispose()
End Try
But how to add directly from data grid view. I enter the values on the empty field and when i click add i want to add it . I know to add in mysql database i need to use this query
query = "insert into base (id, Username, password, Link) values(Which ones ?)"
this is just quick and dirty. in fact you should do this parameterized
you just have to select it so currentrow is not nothing
If Not DataGridView1.CurrentRow Is Nothing Then
Dim id As Integer = DataGridView1.CurrentRow.Cells("ID").Value
Dim username As String = DataGridView1.CurrentRow.Cells("username").Value
Dim pw As String = DataGridView1.CurrentRow.Cells("password").Value
Dim link As String = DataGridView1.CurrentRow.Cells("Link").Value
Dim sqlstr As String = "insert into base (id, Username, password, Link) values(" & id & "," & username & "," & pw & "," & link & ")"
'your code
End If

Why do I keep getting this mysql error?

Hi stackoverflow people!
I have been recently developing a simple vb.net program that connects to a mysql database to register and login users with given credentials. I have used this code to register my users but I keep getting and error (below the code)
Dim insertUser As String = "INSERT INTO users(ID, username, password, email, verif)" _
& " VALUES('','" & Username.Text & "','" & Password.Text & "','" & Email.Text & "','" & currentRandString & "');"
Dim checkUsername As String = "SELECT * FROM users WHERE username='" & Username.Text & "'"
MysqlConn = New MySqlConnection()
MysqlConn.ConnectionString = mysqlconntxt4reg
MysqlConn.Open()
Dim myCommand As New MySqlCommand
myCommand.Connection = MysqlConn
myCommand.CommandText = checkUsername
myAdapter.SelectCommand = myCommand
Dim myData As MySqlDataReader
myData = myCommand.ExecuteReader
If myData.HasRows > 0 Then
MsgBox("Username Already In Use...", MsgBoxStyle.Critical, "Error")
myData.Close()
Else
myData.Close()
Dim myCommand2 As New MySqlCommand
myCommand2.Connection = MysqlConn
myCommand2.CommandText = insertUser
myAdapter.SelectCommand = myCommand2
Dim myData2 As MySqlDataReader
myData2 = myCommand2.ExecuteReader
Mail(Email.Text, currentRandString)
Me.Close()
myData2.Close()
End If
Catch myerror As MySqlException
MsgBox("Error While Connecting To Database:" & vbNewLine & vbNewLine & myerror.ToString, MsgBoxStyle.Critical, "Error")
Finally
MysqlConn.Dispose()
End Try
I have closed all my datareaders before opening other ones so I do not see why this does not work...
Error:
Link to Error Image
I would appreciate any help on this topic!
Thanks
Rodit
I would use the using statement around all the disposable objects to be sure that they release every references to the connection when they are no more needed, but looking at your code, I think you don't need at all the datareaders because you could resolve your problem just with the commands
Dim insertUser As String = "INSERT INTO users(username, password, email, verif)" _
& " VALUES(#p1, #p2,#p3,#p4)"
Dim checkUsername As String = "SELECT COUNT(*) FROM users WHERE username=#p1"
Using MysqlConn = New MySqlConnection(mysqlconntxt4reg)
Using myCommand = New MySqlCommand(checkUsername, MysqlConn)
MysqlConn.Open()
myCommand.Parameters.AddWithValue("#p1", Username.Text)
Dim result = myCommand.ExecuteScalar()
if result IsNot Nothing AndAlso Convert.ToInt32(result) > 0 Then
MsgBox("Username Already In Use...", MsgBoxStyle.Critical, "Error")
Else
Using myCommand2 = New MySqlCommand(insertUser, MysqlConn)
mycommand2.Parameters.AddWithValue("#p1",Username.Text)
mycommand2.Parameters.AddWithValue("#p2",Password.Text )
mycommand2.Parameters.AddWithValue("#p3",Email.Text)
mycommand2.Parameters.AddWithValue("#p4",currentRandString )
myCommand2.ExecuteNonQuery()
Mail(Email.Text, currentRandString)
End Using
End If
End Using
End Using
Of course I have replaced your string concatenations with a parameterized query. This is really an important thing to do to avoid Sql Injection
I have replaced the query that checks the user existence with a scalar operation that can be used with the command ExecuteScalar. Also, in the first query, it seems that you try to insert the field ID with an empty string. I think that the first field (ID) is an autonumber field and, in this case, you don't add it to the insert query and don't pass any value because the database will calculate that field for you.