Reading data from MySQL using VBA
To read data, we will need a database query, as well as to store the results. To create a database query, we simply write it in as a string variable in VBA. To execute the query, we use the open method of a special object called Recordset
, specifying the query, as well as the connection we wish to execute it against. This Recordset
object can store the results of a query and make each field accessible by name. For example, suppose we run the following query:
Dim SQL as String Dim RS as Recordset SQL = "SELECT username, password FROM Login" Set RS = New ADODB.Recordset RS.Open SQL, g_Conn_DSNless
If our query is successful, the RS
variable will contain all of the username and password fields from the Login
table. To access these fields, we use the RS.Fields
method. The next exercise shows a full example of a query that retrieves data through a Recordset
object.
Exercise 11.08 – ReadGenreSales
In this exercise, we are going...