Retrieving Single Database/Cell from table mysql to Vb.net - mysql

I'm making a program in which the label text will change according to the retrieved data. But the only thing/command I found are retrieving data by column or by record. I need to get only a single data/cell.
I already know how to connect and use sql commands in Vb.net by as I said earlier I can't retrieve a single data/cell.
I found a function called mysql_fetch_array but I think It's only for Php not for Vb or I am I mistaken?

This will do it for you !
- you need the limit command added to your query !
- for better performance i suggest using order by !
Dim conn as MySqlConnection
Dim cmd As MySqlCommand
conn = New MySqlConnection("server=localhost;user id=root;password=;database=db_name;")
conn.Open()
cmd = New MySqlCommand("SELECT col_name FROM table_name WHERE col_name='values' LIMIT 1", conn)

Related

How to display all tables in database using vb.net with mySQL xampp?

I am new with mySQL with xampp and VB.net connection and i try to research my question but all of them i cant get it could you please explain and correct my code down below
Try
openCon() ''connection
mysqlCommand.Connection = con
mysqlCommand.CommandText = "SHOW TABLES;"
mysqlAdapter.SelectCommand = mysqlCommand
data.Clear() ''dataset
mysqlAdapter.Fill(data)
con.Close()
ListBox1.DataSource = data.Tables(0)
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
i get nothing when im run this code.
Your code to retrieve the table names is correct. The error is in the assignement to the ListBox datasource without specifying which column of Table(0) should be used to display the lines in the ListBox.
Without setting the DisplayMember property to the name of the column, the Listbox could only display the name of the object that you bind. This object is DataRowView.
The command SHOW TABLES when used to fill a DataAdapter creates a table with a single column and the name of this column is Tables_of_<databasename> but you can also use an indexing approach without giving the exact name of the column
Try
openCon()
mysqlCommand.Connection = con
mysqlCommand.CommandText = "SHOW TABLES;"
mysqlAdapter.SelectCommand = mysqlCommand
data.Clear()
mysqlAdapter.Fill(data)
con.Close()
'' Use whatever is the name of the first column in table returned
ListBox1.DisplayMember = data.Tables(0).Columns(0).ColumnName
ListBox1.DataSource = data.Tables(0)
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
To complete my answer I suggest you to avoid using global variables for the connection, commands and dataadapters. You could only find yourself in trouble when you forget to clear the previous usage of these objects. And the connection is absolutely not the right type of object to keep global. Use the Using statement to create a local connection and destroy it when done.
Finally, remember that SHOW TABLES is a command understood only by MySql. If you ever need to use this same code with a different database you should change that line and use the more standardized query
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = #yourDBNameParameter

Difference between "?" and "#" in visual basic

I just want to ask what is the difference between ? and # when inserting data to mysql in visual basic. So I have this query:
Dim sql As String = "INSERT INTO users(firstname, lastname, position) VALUES(?fname, ?lname, ?pos)"
cmd = New MySqlCommand(sql, conn)
cmd.Parameters.AddWithValue("?fname", TextBox1.Text)
cmd.Parameters.AddWithValue("?lname", TextBox2.Text)
cmd.Parameters.AddWithValue("?pos", TextBox3.Text)
I first use the #param but it is not inserting data to mysql but when I use ?param it inserts data. What is the difference between them?
When CommandType is set to Text, the .NET Framework Data Provider for
ODBC does not support passing named parameters to an SQL statement or
to a stored procedure called by an OdbcCommand. In either of these
cases, use the question mark (?) placeholder.
Direct quote from here:
named parameters with .NET Framework Data Provider for ODBC

MySQL commands in vb code are not working

I've been trying to create a login page that will check if you're an administrator or a customer in my SQL data source. I am not sure why it can't understand the MySQLCommands. I added MySql.Data in the references but this doesn't seem to work.
This is where for example: MySqlConnection and MySqlCommand have blue underlinement.
Dim cmd As MySqlCommand = New MySqlCommand '(strSQL, con)
Password is a reserved word in MySql. If you want to use a field with that name then everytime you use it in your code you should remember to put it between backticks:
`password` = ...
Said that your code has serious problems. You should never concatenate strings coming from the user input to form a sql text. This leads to syntax errors caused by parsing problem and to Sql Injection attacks. You shoul use a parameterized query like this
strSQL = "SELECT name FROM employer WHERE (login=#login AND `password`=#pwd"
Dim cmd As MySqlCommand = New MySqlCommand(strSQL, con)
cmd.Parameters.Add("#login", MySqlDbType.VarChar).Value = strUser
cmd.Parameters.Add("#pwd",MySqlDbType.VarChar).Value = strPaswoord
con.Open()
If cmd.ExecuteScalar() = Nothing Then
....
Finally you should also change the way you get your data because you want to minimize the trips to access the database for performance reason. You should SELECT both the Name and the EMail with a single query and use an MySqlDataReader to get the data.
Other problems present in your code are the lack of appropriate using statement around the connection and the security problem caused by a possible clear text password stored in the database.
#GSerg asked me if I could right click and resolve.
I tried that but that was not an option.
After messing around with the error it appears that I had to write at top:
Imports MySql.Data.MySqlClient
I also had to add backticks when I used the word password for MySQL as #Steve reminded me.
Thank you for your help!

deleting items from sql table in VB.net

I am trying to remove all of the records from an SQL table in VB.net. My code for doing this is:
Dim SQL As String = "DELETE FROM MTable"
Using CN As New OleDb.OleDbConnection(AddPage.DBConnect)
CN.Open()
Dim DBcmd As New OleDb.OleDbCommand(SQL, CN)
DBcmd.ExecuteNonQuery()
CN.Close()
End Using
'SQLDataset.Tables("Mtable").Clear()
MtableTA.Update(SQLDataset)
SQL = "DELETE FROM ITable"
Using CN As New OleDb.OleDbConnection(AddPage.DBConnect)
CN.Open()
Dim DBcmd As New OleDb.OleDbCommand(SQL, CN)
DBcmd.ExecuteNonQuery()
CN.Close()
End Using
' SQLDataset.Tables("ITable").Clear()
ITableTA.Update(SQLDataset)
The Mtable and Itables are the SQL tables, while MtableTA and ItableTA are table adapters.
I also end up getting an error which states
An unhandled exception of type 'System.Data.DBConcurrencyException' occurred in System.Data.dll
Additional information: Concurrency violation: the UpdateCommand affected 0 of the expected 1 records.
The section where this occurss is not provided in the code above, but is a call to MtableTA.update(SQLDataset). Any help would be very much appreciated. I'm also using OLEDB if that helps.
You have directly deleted the rows bypassing the TableAdapter methods to do that. So it is highly probable that when you call the Update there are some conflicts with data changed on the TableAdapter and no more available in the database.
After removing the rows directly using OleDbCommand.ExecuteNonQuery you should simply refresh the TableAdapters to sync them with the real situation on your physical database table
SQLDataset.Tables("ITable").Clear()
ITableTA.Adapter.Fill(SQLDataSet.ITable)

How in VB.net we can encode string for SQL

For example, in sql
all ` should be replaced with `` right?
Well, is there a function built in by vb.net that does that sort of thing already?
That way I do not have to encode it.
By the way, I do not access sql database directly. Basically I am creating a text file and that text file contains raw sql statements. Most of the answers deal with accessing sql data directly.
I don't think so as I think the only case where something like this would be relevant is if you were doing inline SQL Commands without parameters.
This has a risk of SQL Injection, and therefore you should create commands like this:
Dim cmd As New SqlCommand("UPDATE [TableA] SET ColumnA=#ColumnA WHERE ID=#ID", Conn)
cmd.Parameters.Add("#ColumnA", SqlDbType.NVarChar).Value = txtColumnA.Text
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = ID
cmd.ExecuteNonQuery()
Dont try and do this! I know you are trying to avoid SQL Injection so you are to be commended for thinking about security. However rolling your own sanitisation routine is something that is easy to get wrong.
Use parameters in your query along the lines of
cmd.CommandText = "select * from customer where id=?id";
cmd.Parameters.AddWithValue("?id",CustomerIDValue);
If you are using a string then you'll be using " in your code so you won't need to escape these characters.
Dim mySql As String = "SELECT `MyColumn` FROM `Table`"