Insert in MySql database DataGrid Values - mysql

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

Related

Populate Label in VB from MySQL select query

I have found a few articles that are similar to my question, and I have tried the suggestions in those articles and none of them have worked for me. What I need seems to be fairly simple and straight forward. (I am able to complete this same action with SQL Server, just not with MySQL. This 'description' information must come a MySQL db)
I have a Listbox and as the user clicks on listbox items, I would like a 'description' label to update with a value pulled from a MySQL database.
I created a public sub in the Module, and I'm calling the sub from the Listbox1_SelectedIndexChanged event (also tried Listbox1_mouseclick event).
However, everything I have tried does not update the label. Any suggestions would be greatly appreciated.
here is the code being used to pull and attempt to populate the label:
Dim conn As New MySqlConnection(My.Resources.MySqlstr)
Try
conn.Open()
Dim cmd As MySqlCommand = New MySqlCommand("select Description from resourceaccess where tid = '" & ReportPicker.ListBox1.ValueMember & "' ", conn)
Dim reader As MySqlDataReader = cmd.ExecuteReader()
While reader.Read()
ReportPicker.Label3.Text = reader.GetString("Description")
End While
reader.Close()
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Close()
End Try
I don't know if something else is wrong too but this definitely is:
Dim cmd As MySqlCommand = New MySqlCommand("select Description from resourceaccess where tid = '" & ReportPicker.ListBox1.ValueMember & "' ", conn)
Apart from the fact that you should be using a parameter there, the use of ValueMember can't possibly be right. That's the name of a column, not a value from that column. You should be using SelectedValue, which is the value from that column for the item that's selected.
here is what worked:
Dim cs As String = My.Resources.MySqlstr
Dim stm As String = "select Description from resourceaccess where resource = '" & ReportPicker.ListBox1.Text & "' "
Dim conn As MySqlConnection = New MySqlConnection(cs)
Try
conn.Open()
Dim cmd As MySqlCommand = New MySqlCommand(stm, conn)
ReportPicker.Label3.Text = Convert.ToString(cmd.ExecuteScalar())
Catch ex As MySqlException
MessageBox.Show(ex.Message)
Finally
conn.Close()
End Try

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)

Display an error if row already exists in insert data into SQL Server database using vb 2010

I have written a program to connect to SQL Server and insert data.
When I insert data into database with same StrUserID in SQL Server, it inserted data a second time, without an error Like that image in sql..
I need to ensure that data is only inserted into the database once, and if a row with the same StrUserID already exists, I need to display a message telling him "such a user name already exists".
Like that photo...
This is my code to insert data into database..
Query = "insert into TB_User (StrUserID,password) Values ('" & TextBox1.Text & "' , '" & TextBox2.Text & "')"
My second problem: when user create/insert data into sql I need to make password row change to MD5 not a normal password like the first photo in the first row...
Imports System.Data.SqlClient
Public Class Form2
Public mysqlconn As SqlConnection
Public command As SqlCommand
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
mysqlconn = New SqlConnection
mysqlconn.ConnectionString =
"Data Source=MY-PC\SQLEXPRESS; initial catalog=SRO_VT_ACCOUNT;user id=sa;password=123"
Dim reader As SqlDataReader
Try
mysqlconn.Open()
Dim Query As String
Query = "insert into TB_User (StrUserID,password) Values ('" & TextBox1.Text & "' , '" & TextBox2.Text & "')"
command = New SqlCommand(Query, mysqlconn)
reader = command.ExecuteReader
MessageBox.Show("Done")
mysqlconn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
End Class
1 Build a unique constraint and handle the appropriate exception:
ALTER TABLE TB_User ADD CONSTRAINT UQ_USER_ID UNIQUE (StrUserID)
https://msdn.microsoft.com/en-us/library/ms190024(v=sql.120).aspx
2 Try HASBYTES function:
insert ...
values (:UserID, HASHBYTES('MD5', pwd))
https://msdn.microsoft.com/ru-ru/library/ms174415(v=sql.120).aspx

How do you insert a binary reader to string query for mysql?

I'm learning how to upload images into MySql database. Before you all get cranky and tell me that it's bad practice to upload images into mysql database, I AGREE WITH YOU, but it's for a school project and that's what the school wants.
This is what I found on the net and it works. But I would like to understand it more and maybe modify it to fit my custom subs. Also the datatype for the images is blob
Dim strFileName as String 'This is the file path
Dim con As MySqlConnection = New MySqlConnection(cnn.ConnectionString)
Dim cmd As MySqlCommand
Dim fs As FileStream
Dim br As BinaryReader
Dim FileName As String = strFileName.ToString
Dim ImageData() As Byte
fs = New FileStream(FileName, FileMode.Open, FileAccess.Read)
br = New BinaryReader(fs)
ImageData = br.ReadBytes(CType(fs.Length, Integer))
br.Close()
fs.Close()
If File.Exists(strFileName) = False Then MsgBox("Cannot locate file") : Return
Dim CmdString As String = "INSERT into tbl_maps(map_name,map_floor,map) Values('" & txtMapName.Text & "','" & cmbMapsFloor.Text & "',#Image)"
cmd = New MySqlCommand(CmdString, con)
cmd.Parameters.AddWithValue("Image", ImageData)
con.Open()
Now my question is, is there a way to insert ImageData into a string for the MySqlCommand? This is how I usually insert data into the database.
Public Sub RunQuery()
On Error Resume Next
dr.Close()
InitQuery()
cmd.ExecuteNonQuery()
End Sub
Public Sub InitQuery()
With cmd
.CommandText = sql
.Connection = cnn
End With
End Sub
Private Sub something()
sql = "INSERT into tbl_maps(map_name,map_floor) Values('" & txtMapName.Text & "','" & cmbMapsFloor.Text & "')"
RunQuery()
MsgBox("Data saved successfully") 'or some way to check the data inserted
End Sub
I was hoping for something that would maybe look like this
sql = "INSERT into tbl_maps(map_name,map_floor,map) Values('" & txtMapName.Text & "','" & cmbMapsFloor.Text & "','" & ImageData & "')"
RunQuery()
But I know that's not correct because sql is a string and ImageData is not. I'm just looking for a way to avoid using cmd.Parameters.AddWithValue("Image", ImageData) or at the very least integrate it into my RunQuery sub.
P.S.: Not that it really matters but I like 1 line code sets. Because I read lines like I read sentences. Example:
If RecordNotExist() = true then Msgbox("Record not found") : txtsearch.selectall() : txtsearch.focus() : return
Translation: If no records match the search query, search for something else.

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.