Select single row from database using mysql connector .NET - mysql

I've just heard about the mysql connector and I want now to take a single row from my database(every row is unique). I don't want to use a loop because it would be useless(only for one row?..). I know how to connect to a database but I just can't figure out how to select a single row. This is my code :
''Register user in dtb
cmd = New MySqlCommand("INSERT INTO `users`(`name`, `ip`, `status`) VALUES ('" & My.User.Name.Split("\")(1) & "','" & ip_temp & "','1')", conn)
cmd.ExecuteNonQuery()
''Get user's Id from dtb -->this is where I'm having troubles
cmd = New MySqlCommand("SELECT 'id' FROM `users` WHERE name='" & My.User.Name.Split("\")(1) & "' ", conn)
dtb_data = cmd.ExecuteScalar
Debug.Print(dtb_data(0))
It doesn't work. The error is: "Unable to cast object of type 'System.String' to type 'MySql.Data.MySqlClient.MySqlDataReader'." (of course...). I know that it must look something like "dtb_data['id']" (from php) but this command doesn't exist in VB.Net. What should I do?

ExecuteScalar returns single value from single row. Therefore in your case dtb_data must be declared as String. Most probably this is mistake and it should be declared as Int or Long as you probably want to return id, not 'id' as literal.
So the full example should be:
Dim dtb_data as Long
cmd = New MySqlCommand("SELECT id FROM `users` WHERE name='" & My.User.Name.Split("\")(1) & "' ", conn)
dtb_data = cmd.ExecuteScalar
Debug.Print(dtb_data)

Related

Im trying to insert a data into database using vb

I am trying to add a new data in mySql database using vb . But the error always says [unit_type] is not allowed to be null . I even changed the column's setting in the main database . I disabled the not null checkbox .
Dim datetoday = Date.Today
Try
command = "INSERT INTO assets_table ([date_created], [unit_type]) VALUES ('" & datetoday & "' , '" & frm_viewAssets.lbl_fetch.Text & "')"
Dim cmd As MySqlCommand = New MySqlCommand(command, myconn.open())
cmd.Parameters.Add(New MySqlParameter("date_created", CType(datetoday, String)))
cmd.Parameters.Add(New MySqlParameter("unit_type", CType(frm_viewAssets.lbl_fetch.Text, String)))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myconn.close()
Catch ex As Exception
myconn.close()
End Try
You did the right thing by trying to use parameters but you did it wrong. You added the parameters to the command but, instead of using parameter place-holders in your SQL, you still inserted the literal values. This:
command = "INSERT INTO assets_table ([date_created], [unit_type]) VALUES ('" & datetoday & "' , '" & frm_viewAssets.lbl_fetch.Text & "')"
should be this:
command = "INSERT INTO assets_table ([date_created], [unit_type]) VALUES (#date_created, #unit_type)"
and then I think that you will need to add the "#" prefix to the parameter names when you create them as well.
Keep the database objects local so you can be sure they are closed and disposed. Using...End Using blocks will handle that for you even if there is an error.
Don't open the connection until directly before the .Execute.
I assumed the type of date_created to be a Date.
It can improve the efficiency of your sql to include the datatypes of your parameters.
If all you are doing in your Try/Catch is closing the connection you are just swallowing errors.
Private Sub OPCode()
Dim datetoday = Date.Today
Dim Command = "INSERT INTO assets_table ([date_created], [unit_type]) VALUES (#date_created , #unit_type);"
Using myconn As New MySqlConnection("Your connection string"),
cmd As New MySqlCommand(Command, myconn)
cmd.Parameters.Add("#date_created", MySqlDbType.Date).Value = datetoday
cmd.Parameters.Add("#unit_type", MySqlDbType.VarChar).Value = frm_viewAssets.lbl_fetch.Text
myconn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub

save result mysql query to variable in VB net

i have vb such as like this :
Sub inputdata()
Try
koneksi.Open()
***sql2 = "SELECT code_cust from customer where ('nama_cust= " & Me.cbcust.Text & "')"
cmd = New MySqlCommand(sql2, koneksi)
sql3.text=cmd.ExecuteNonQuery()***
sql = "insert into hsmaster(nohs,detailhs,beamasuk,satuanhs,idcust,asal) values ('" & Me.txtnohs.Text & "',"
sql += "'" & Me.rtdetail.Text & " ',"
sql += "'" & Me.txtbm.Text & " ',"
sql += "'" & Me.txtsatuan.Text & " ',"
sql += "'" & sql3 & " ',"
sql += "'" & Me.Cbcountry.Text & " ')"
cmd = New MySqlCommand(sql, koneksi)
cmd.ExecuteNonQuery()
MessageBox.Show("Insert data berhasil dilakukan")
Catch ex As Exception
MessageBox.Show("Insert data Gagal dilakukan")
Finally
koneksi.Close()
End Try
So i want save result of quert sql3 to slq3 , but the result was -1
Please advace ...
sql2 was query to customer table with clause name of customer was loading from combo box customer.
cbcust.text was from combo box loading data from table customer.
thanks for any kind help and sugestion.
ExecuteNonQuery is only for inserts/updates/deletes, queries that you aren't expecting to retrieve data back from. The -1 you are seeing is what databases return when executing a non-query to indicate whether the command was successful. You are correct to use ExecuteNonQuery on your second insert, but for your first select query if you want a value returned, you have to use
sql3.text = cmd.ExecuteScalar
or use a datareader
Dim dr As MySqlDataReader
dr = cmd.ExecuteReader
'check to make sure dr isnot nothing and read it, then
Dim returnValue as string = dr(code_cust)
ExecuteScalar is used for returning a single value and would probably work best in your case, datareader is used when expecting multiple columns and/or rows
You should be using parameters in your query too, but if using quotes like you are then:
***sql2 = "SELECT code_cust from customer where ('nama_cust= " & Me.cbcust.Text & "')"
needs the single quote moved like this:
***sql2 = "SELECT code_cust from customer where (nama_cust= '" & Me.cbcust.Text & "')"
because right now, that's a syntax error

Checking if the user is already registered

I'm trying to create a register for using mysql table as if username and pass is already added it output a msgbox saying you are already registered but what happen is that it always add it even if it already exists ..
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cn As New SqlConnection
Dim cmd As New SqlCommand
Dim cmd2 As New SqlCommand
Dim dr As SqlDataReader
cn.ConnectionString = "Server=localhost;Database=test;Uid=sa;Pwd=fadyjoseph21"
cmd.Connection = cn
cmd.CommandText = "INSERT INTO test2(Username,Password) VALUES('" & TextBox1.Text & "','" & TextBox2.Text & "')"
cmd2.CommandText = cmd.CommandText = "SELECT username, password FROM test2 WHERE username = '" & TextBox1.Text & "' and password = '" & TextBox2.Text & "'"
cn.Open()
MsgBox("Registered")
cmd.ExecuteNonQuery()
dr = cmd.ExecuteReader
If dr.HasRows Then
MsgBox("You're already registered")
End If
End Sub
End Class
You never actually check to see if the username exists.
You define a query here:
cmd2.CommandText = cmd.CommandText = "SELECT username, password FROM test2 WHERE username = '" & TextBox1.Text & "' and password = '" & TextBox2.Text & "'"
But never execute that query. Instead, you just execute the INSERT query:
dr = cmd.ExecuteReader
So the INSERT is always performed. And since an INSERT doesn't return rows, you don't see the message box.
First thing's first, fix your SQL injection vulnerability. (Personal policy, I don't like writing SQL-injectable code in an answer.) Use query parameters instead of directly concatenating user input as code:
cmd2.CommandText = "SELECT * FROM test2 WHERE username = #Username"
cmd2.Parameters.Add("#Username", SqlDbType.VarChar, 50).Value = TextBox1.Text
dr = cmd2.ExecuteReader
If dr.HasRows Then
MsgBox("You're already registered")
Return
End If
Note a couple of things here:
The use of a query parameter. I had to guess on the type and size of the column in the database, adjust that as necessary.
Only executing this one query. Don't try to execute both queries at the same time, perform the first one and then perform the second one.
You don't need, or even want, to include the password in this query. You're checking if the username already exists, that's all.
Return after showing the message, so the rest of the function doesn't execute.
Then, after that is done, you can perform the INSERT operation:
cmd.CommandText = "INSERT INTO test2(Username,Password) VALUES(#Username,#Password)"
cmd.Parameters.Add("#Username", SqlDbType.VarChar, 50).Value = TextBox1.Text
cmd.Parameters.Add("#Password", SqlDbType.VarChar, 50).Value = TextBox2.Text
cmd.ExecuteNonQuery()
This will perform the INSERT operation. So if the Return above was never encountered then the username is unique and can be inserted.
Also: You should not be storing user passwords in plain text. This is grossly irresponsible to your users and exposes their private data to attackers. Instead, obscure the password with a one-way hash so that it can't be read in its original form.
A couple other things:
Use meaningful variable names. The whole reason you were having this problem was because you were getting confused between cmd and cmd2. If your variable names carry semantic meaning, your code is a lot easier to read and understand.
Make use of the Using block when you have disposable resources, such as a database connection. In general you want to open, use, and close a database connection in as small a scope as possible. Leaving open connections hanging around is a Bad Thing.
Add unique key constraint on username and hence when it already exist it will throw duplicate entry exception.
Secondly, never save plain text password in Database, it must be hasheh and encrypted. I would suggest to better use Bcrypt of atleast level 10 to generate hashed password and also use Bcrypt dynamic salt which is mostly preferred now.
Thirdly, always use parameterized query to avoid your program from mysql injection.
For example:-
Normal:
SELECT * FROM customers WHERE username = 'timmy'
Injection:
SELECT * FROM customers WHERE username = '' OR 1''

vb.net and sql database

I have got a datagrid view which is filled by a table on my microsoft mysql database my problem is i need to select a row and its values then appear in the text boxes which i have solved. but now if any changes are to occur i want to create an update function to update the records with the changes made. I've tried but failed until now.
Public Sub AddMember(FirstName As String, Surname As String, Admin As Integer)
Try
Dim strInsert As String = _
"UPDATE test Firstname='this should be the value entered in the text box' " & _
"WHERE Firstname = 'this should equal to the value selected from the datagrid view'"
MsgBox(strInsert)
SQLCon.Open()
SQLCmd = New SqlCommand(strInsert, SQLCon)
SQLCmd.ExecuteNonQuery()
SQLCon.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
I you are working with MySQL then you should be using MySqlCommand instead of SqlCommand. Also use a MySqlConnection. You find both in the MySql.Data.MySqlClient namespace.
You also will need to download and install the "Connector/Net" and add a reference to MySql.Data.dll in your project if you have not done this already .
Also use command parameters instead of string concatenation. This is both safer (See: SQL injection) and easier, as you do not have to worry about formatting strings, numbers and dates the right way for SQL.
Dim sql As String = "UPDATE tst SET FirstName=#fn, Surname=#sn WHERE Id=#id"
Using conn = New MySqlConnection(connectionString)
Using cmd = New MySqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#fn", FirstName)
cmd.Parameters.AddWithValue("#sn", Surname)
cmd.Parameters.AddWithValue("#id", id)
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Note that the WHERE-clause should identify the database row by its primary key. In MySQL a primary key is best created as AUTO_INCREMENT column. In no case use the first name in order to identify the row, as serveral persons can have the same first name. See: Using Primary Keys and SQL PRIMARY KEY Constraint.
check syntax for update here
so change your query as follows:
Dim strInsert As String = " update test Set FirstName= '" & FirstName & "'," & _
"Surname='" & Surname & "'," & _
"admin='" & Admin & "')"
This is the query you should use.
Parameters with # are actually values you're sending to SQL.
Update test Set FirstName=#FirstName where Id=#Id

My query in mysql is correct but there is something wrong in my code when I am applying it to VB.net

My query is correct in mysql but there is something wrong in my code when I am applying it to VB.net. Im using textpass.Text as a textbox.
cmd = New Odbc.OdbcCommand("INSERT INTO errorlog(pword) VALUES ('Wrong','" &
Trim(txtpass.Text) & "'", con)
This is my working query in my sql
INSERT INTO pcba_info.errorlog(pword) VALUES ('Wrong ');
cmd = New Odbc.OdbcCommand("INSERT INTO errorlog(pword) VALUES ('Wrong','" &
Trim(txtpass.Text) & "'", con)
errorlog(pword) ---> Here your specifing single column name but
VALUES ('Wrong','" & Trim(txtpass.Text) & "'" -----> your passing two values
So its throw error