MySQL Query Browser Error Data truncated for column - mysql

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

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

inserting data on mysql using vb.net with VS2010

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)

SQL Connection error 40 000webhost with Visual Basic

I am pretty sure I have all of my information right here, but I keep getting this error
http://puu.sh/qoZDQ/7294d6e682.png
The code I used: (Not mine)
I have the right username password and database name (I think)
'SET THE CONNECTION BETWEEN VISUAL BASIC AND MYSQL DATABASE
Dim con As SqlConnection = New SqlConnection("Data Source=mysql9.000webhost.com;" & "Initial Catalog=databasename;" & "User ID=username;" & "Password=password;")
'A SET OF COMMAND IN MYSQL
Dim cmd As New SqlCommand
'SET A CLASS THAT SERVES AS THE BRIDGE BETWEEN A DATASET AND DATABASE FOR SAVING AND RETRIEVING DATA.
Dim da As New SqlDataAdapter
'SET A CLASS THAT CONSISTS SPECIFIC TABLE IN THE DATABASE
Dim dt As New DataTable
Dim sqlQuery As String
Dim result As Integer
Private Sub register(ByVal sqlQuery As String)
Try
'OPENING THE CONNECTION
con.Open()
'HOLDS THE DATA TO BE EXECUTED
With cmd
.Connection = con
.CommandText = sqlQuery
End With
'EXECUTE THE DATA
Result = cmd.ExecuteNonQuery
'CHECKING IF THE DATA HAS BEEN EXECUTED OR NOT
If result > 0 Then
MsgBox("User has been registered.")
Else
MsgBox("Failed to register the user.")
End If
con.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub login(ByVal sqlQuery As String)
Try
con.Open()
With cmd
.Connection = con
.CommandText = sqlQuery
End With
'FILLING THE DATA IN A SPECIFIC TABLE OF THE DATABASE
da.SelectCommand = cmd
dt = New DataTable
da.Fill(dt)
'DECLARING AN INTEGER TO SET THE MAXROWS OF THE TABLE
Dim maxrow As Integer = dt.Rows.Count
'CHECKING IF THE DATA IS EXIST IN THE ROW OF THE TABLE
If maxrow > 0 Then
MsgBox("Welcome " & dt.Rows(0).Item(4))
Else
MsgBox("Account does not exist.")
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
con.Close()
End Sub
Private Sub btn_Register_Click(sender As Object, e As EventArgs) Handles btn_Register.Click
sqlQuery = "INSERT INTO `dbuser` ( `user_name`, `user_username`, `user_pass`, `user_type`, `user_steamid`)" & "VALUES ('" & txtname.Text & "','" & txtusername.Text & "','" & txtpassword.Text & "','" & cbotype.Text & "','" & txtsteamid.Text & "')"
register(sqlQuery)
End Sub
Private Sub btn_Login_Click(sender As Object, e As EventArgs) Handles btn_Login.Click
sqlQuery = "SELECT * FROM `dbuser` WHERE user_username ='" & txtusername.Text & "' AND user_pass = '" & txtpassword.Text & "'"
login(sqlQuery)
End Sub
I used the database info from here http://puu.sh/qoZXo/a391cba854.jpg (Also not my info just an example so I dont post my info publicly)
I fixed my issue with the help of what Plutonix commented
MySql is not the same thing as Microsoft SqlServer – Plutonix
So I did some googling and found this: https://dev.mysql.com/downloads/connector/net/
This is the .Net framework for MySql (I think thats the right terms)
anyhow installing this then changing the top line of my code from
imports System.Data.SqlClient
To:
imports MySql.Data.MySqlClient
and changing the sql variables in the code to MySql variables by just adding My to the first bit, and it seems to work "better" I now have a new issue, but its with 000webhosts mysql database, not the code.

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

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.