cannot insert path file address to mysql using vb.net - mysql

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

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

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)

Insert data to MySql and display in datagridveiw

Recently i developed a pos but i have an problem inserting the data and displaying the names of the table in datagrid view
here is some code :
Dim Query As String
Query = "insert into baza.artikli(barkod,naziv,kupovna,prodazna,kolicina,proizvoditel,opis) values ('" & TextBoxBarkod.Text & "','" & TextBoxNaziv.Text & "','" & kupovnacena & "','" & prodaznacena & "','" & kolicina & "','" & TextBoxProizvoditel.Text & "','" & TextBoxOpis.Text & "')"
COMMAND = New MySqlCommand(Query, konekcija)
READER = COMMAND.ExecuteReader
MessageBox.Show("Артиклот е успешно внесен !")
TextBoxBarkod.Text = ""
TextBoxKupovna.Text = ""
TextBoxNaziv.Text = ""
TextBoxOpis.Text = ""
TextBoxProdazna.Text = ""
TextBoxProizvoditel.Text = ""
TextBoxKolicina.Text = ""
konekcija.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
konekcija.Dispose()
And i tried:
Private Sub prikazitabela()
konecija = New MySqlConnection
konecija.ConnectionString =
"server=localhost;userid=root;password=root;database=bazaartikli123"
Dim SDA As New MySqlDataAdapter
Dim bazaDataSet As New DataTable
Dim bajndsors As New BindingSource
Try
konecija.Open()
Dim Query As String
Query = "select barkod as 'Баркод',naziv as 'Назив на артикал',kupovna as 'Куповна цена',prodazna as 'Продажна цена',opis as'Опис',ddv as 'ДДВ',makproizvod as 'Македонски прозивод' from bazaartikli123.artikli"
COMMAND = New MySqlCommand(Query, konecija)
SDA.SelectCommand = COMMAND
SDA.Fill(bazaDataSet)
bajndsors.DataSource = bazaDataSet
DataGridView1.DataSource = bajndsors
SDA.Update(bazaDataSet)
konecija.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
konecija.Dispose()
End Try
End Sub`
There are several things that can be improved, starting with using SQL parameters and executing your query:
Dim Query As String = <sql>
insert into baza.artikli
(barkod,naziv,kupovna,prodazna,kolicina,proizvoditel,opis)
values (#p1,#p2,#p3,#p4,#p5,#p6,#p7 )
</sql>.Value
Using dbcon As New MySqlConnection(MySQLConnStr)
Using cmd As New MySqlCommand(Query, dbcon)
' I dont really know what datatype these really are
cmd.Parameters.Add("#p1", MySqlDbType.VarChar).Value = TextBoxBarkod.Text
cmd.Parameters.Add("#p2", MySqlDbType.DateTime).Value = DTPNaziv.Value
cmd.Parameters.Add("#p3", MySqlDbType.Int32).Value = Convert.ToInt32(Textkupovna.Text)
' ...
dbcon.Open()
' this was missing:
cmd.ExecuteNonQuery()
End Using
dt = New DataTable
Using cmd As New OleDbCommand("SELECT * FROM baza.artikli")
dt.Load(cmd.ExecuteReader())
dgv2.DataSource = dt
End Using
End Using
I used an XML literal for the SQL mainly to avoid scrolling here, but it can make your code much more readable
There is little context for the code in the question, but connections ought be created as needed; DBCommand objects are highly query specific, so they too ought be created as needed rather than using global ones.
Use Using blocks to assure that DbConnections and other objects with a Dispose() method are properly disposed. The code closes, but does not Dispose of the connection.
Use SQL Parameters always. These assure the correct data type is passed, avoid the cruft of " Foo -'" & foovar & "' AND ..." in code, protect against special characters in strings as well as prevent SQL injection attacks.
Then cmd.ExecuteNonQuery() performs the insert.
After that, you can run a new query to get whatever data you want to display. Note that you do not need to create a DataAdapter to fill a table. It is not clear what you want to display, so that will also have to be modified for what you want.
When AutoGenerateColumns is True, they will be created when you set the datasource and the column names (== 'names of the table' ?) will automatically show. If you want different text to display for the headers, you can either set them manually or uses aliases for them in your SQL, as shown on a previous answer

mysql to vb.net command

please help me on this code
when i run this code i having a error " invalid attempt to read when reader is close"
q = "select * from test.table1"
com = New MySqlCommand(q, con)
rs = com.ExecuteReader
While rs.Read
Dim ln = rs.GetInt64("id1")
Dim fn = rs.GetString("name")
If fn = TextBox1.Text Then
rs.Close()<this line having error>
f1 = "INSERT INTO test.table2(id2,fname,Mname,name)VALUE('" & "null" & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & Val(ln) & "')"
com = New MySqlCommand(f1, con)
com.ExecuteNonQuery()
End If
End While
con.Close()
rs.Dispose()
MsgBox("successfully inserted the data")
If you enter the if block you close the MySqlDataReader because you need to run an insert command, but when a connection is busy serving a DataReader cannot be used to serve another command. However the code continues and the next loop is executed. At this point if you try to read using the previous variable you get the error because the MySqlReader has been closed at the previous loop.
You could fix the problem opening a second connection using the connectionstring from the first connection. This seems to be the required path with MySql .NET Adapter because it doesn't support the MultipleActiveResultSets keyword in the connection string like SqlServer
While rs.Read
Dim ln = rs.GetInt64("id1")
Dim fn = rs.GetString("name")
If fn = TextBox1.Text Then
f1 = "INSERT INTO ........"
Using con2 = new MySqlConnection(con.ConnectionString)
con2.Open()
com = New MySqlCommand(f1, con2)
com.ExecuteNonQuery()
End Using
End If
End While