MySQL Sample for Visual Basic 6.0 - read/write - mysql

I'd like to find a simple example of working with remote MySQL base. I know, there are some tutorial over the internet, explaining how to set up ADODB.Connection and connectionstrings, but I couldnt make it work. Thanks for any help!

Download the ODBC connector from the MySQL download page.
Look for the right connectionstring over here.
In your VB6 project select the reference to Microsoft ActiveX Data Objects 2.8 Library. It's possible that you have a 6.0 library too if you have Windows Vista or Windows 7. If you want your program to run on Windows XP clients too than your better off with the 2.8 library. If you have Windows 7 with SP 1 than your program will never run on any other system with lower specs due to a compatibility bug in SP1. You can read more about this bug in KB2517589.
This code should give you enough information to get started with the ODBC connector.
Private Sub RunQuery()
Dim DBCon As adodb.connection
Dim Cmd As adodb.Command
Dim Rs As adodb.recordset
Dim strName As String
'Create a connection to the database
Set DBCon = New adodb.connection
DBCon.CursorLocation = adUseClient
'This is a connectionstring to a local MySQL server
DBCon.Open "Driver={MySQL ODBC 5.1 Driver};Server=localhost;Database=myDataBase; User=myUsername;Password=myPassword;Option=3;"
'Create a new command that will execute the query
Set Cmd = New adodb.Command
Cmd.ActiveConnection = DBCon
Cmd.CommandType = adCmdText
'This is your actual MySQL query
Cmd.CommandText = "SELECT Name from Customer WHERE ID = 1"
'Executes the query-command and puts the result into Rs (recordset)
Set Rs = Cmd.Execute
'Loop through the results of your recordset until there are no more records
Do While Not Rs.eof
'Put the value of field 'Name' into string variable 'Name'
strName = Rs("Name")
'Move to the next record in your resultset
Rs.MoveNext
Loop
'Close your database connection
DBCon.Close
'Delete all references
Set Rs = Nothing
Set Cmd = Nothing
Set DBCon = Nothing
End Sub

Related

create linked tables with vba through odbc connection (MySql) in excel

I have an excel file, which needs to have a connection to a mysql database with odbc. I am aware of the option to do it through UI, but i would prefer not to (data - get_data - from other sources - from odbc). I have made it in access, the linked tables are the same as the ones that i can create through the UI. In excel, i have not found a solution for this.
For now, i have some weird code that establishes the connection just fine, but creates weird tables in excel when trying to get the data from the database (numbers being converted to dates, some data not even loading, ...).
Here is the code that i have for now in excel:
Function connect2mssql()
Dim con As ADODB.connection
Dim rs As ADODB.Recordset
Set con = New ADODB.connection
Dim SQL As String
con.Open "DRIVER={MySQL ODBC 5.3 Unicode Driver};SERVER=192.168.12.192;DATABASE=rezervni_deli;UID=vzdrzevalec;PWD=unichem"
''####################
SQL = "SELECT * FROM rezervni_deli;"
Set rs = New ADODB.Recordset
rs.Open SQL, con
For intColIndex = 0 To rs.Fields.Count - 1
Worksheets("rezervni_deli").Range("A1").Offset(0, intColIndex).Value = rs.Fields(intColIndex).Name
Next
Worksheets("rezervni_deli").Range("A2").CopyFromRecordset rs
''####################
SQL = "SELECT * FROM p_linija;"
Set rs = New ADODB.Recordset
rs.Open SQL, con
For intColIndex = 0 To rs.Fields.Count - 1
Worksheets("p_linija").Range("A1").Offset(0, intColIndex).Value = rs.Fields(intColIndex).Name
Next
Worksheets("p_linija").Range("A2").CopyFromRecordset rs
''####################
rs.Close
Set rs = Nothing
End Function

MySQL query error (ODBC 3.51)

I'm trying to execute query in a VB6 app.
Here is my code:
Dim con As ADODB.Connection
Set con = New ADODB.Connection
con.ConnectionString = "Driver={MySQL ODBC 3.51 Driver}; Server=***; Database=***; Username=***; Password=***; Option=3"
con.Open
Dim cmd As New ADODB.Command
With cmd
.ActiveConnection = con
.CommandText = "SELECT COD_CONFIG FROM FDT_CONFIG"
.CommandType = adCmdText
End With
Dim rs As New ADODB.Recordset
rs.CursorLocation = adUseClient
rs.Open cmd, , adOpenStatic, adLockOptimistic
I've hidden some information in the connection string but in my app I'm using the correct values.
I can successfully open the connection, but when I try to execute the query I get:
"Execution error '2147467259 (800004005)' : unspecified error"
Can someone tell me where I'm going wrong?
If you want to assign a Command object's ActiveConnection to an existing Connection object, you must use Set:
With cmd
Set .ActiveConnection = con
....
End With
It's a little confusing because you can also assign a string to the ActiveConnection property and ADO will create an ad-hoc connection for you. In that case, you wouldn't use Set because you're just assigning a value to an intrinsic type (string):
With cmd
.ActiveConnection = "Driver={MySQL ODBC 3.51 Driver}; Server=***; Database=***; Username=***; Password=***; Option=3"
...
End With
So the property can be used multiple ways. In your scenario, however, since you're assigning an object reference, you'll need to use the Set keyword.

Calling Sql Server 2008 stored procedure from vb6 with datetime

I have a legacy vb6 app which accesses databases running on both SQL2000 and SQL2008 databases.
When calling a stored procedure with a datetime parameter from vb6 using an adDBTimeStamp input parameter, the complete date time, including seconds is passed to the stored procedure.
When calling the same stored procedure in an SQL2008 r2 database, the seconds are always zero.
EDIT:
Create the following stored procedure on both a SQL2000 database and an SQL2008 R2 database.
CREATE PROCEDURE [dbo].[TestDate] (#DateAndTime DATETIME)
AS
SET NOCOUNT ON
BEGIN
SELECT #DateAndTime AS DateAndTime
END
Then build a VB6 app with the following command button event method:
Private Sub Command_Click()
Dim SQL2000_ConnectionString As String
Dim SQL2008_ConnectionString As String
Dim DateOnly As Date
Dim DateAndTime As Date
DateAndTime = DateTime.Now
SQL2000_ConnectionString = "Driver={SQL Server};Server=<SQL2000ServerName>;UID=<UserName>;pwd=<Password>;Database=<DataBaseName>;dsn=''"
SQL2008_ConnectionString = "Provider=SQLNCLI10;DataTypeCompatibility=80;Server=<SQL2008ServerName>;Database=<DataBaseName>;User Id=<UserName>;Password=<Password>;"
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim Msg As String
Set conn = New ADODB.Connection
conn.ConnectionTimeout = 300
Call conn.Open(SQL2000_ConnectionString)
Set cmd = New ADODB.Command
With cmd
.CommandType = adCmdStoredProc
Set .ActiveConnection = conn
.CommandType = adCmdStoredProc
.CommandText = "TestDate"
.CommandTimeout = 60
Call .Parameters.Append(.CreateParameter("#dtDateAndTime", adDBTimeStamp, adParamInput))
.Parameters("#dtDateAndTime").Value = DateAndTime
Set rs = .Execute
End With
If Not rs.EOF Then
Msg = "DateTime:" & rs.fields("DateAndTime").Value
Call MsgBox(Msg)
End If
Call conn.Close
Set conn = New ADODB.Connection
conn.ConnectionTimeout = 300
Call conn.Open(SQL2008_ConnectionString)
Set cmd = New ADODB.Command
With cmd
.CommandType = adCmdStoredProc
Set .ActiveConnection = conn
.CommandType = adCmdStoredProc
.CommandText = "TestDate"
.CommandTimeout = 60
Call .Parameters.Append(.CreateParameter("#dtDateAndTime", adDBTimeStamp, adParamInput))
.Parameters("#dtDateAndTime").Value = DateAndTime
Set rs = .Execute
End With
If Not rs.EOF Then
Msg = "DateTime:" & rs.fields("DateAndTime").Value
Call MsgBox(Msg)
End If
Call conn.Close
End Sub
When you execute the vb6 app, the first message box displays with the date and time including seconds. The second message box has the seconds display as zero.
I am seeing the same thing when I log the input parameters within the databases.
It appears as though the call to the SQL2008 R2 database is truncating the seconds of the input parameter.
2nd EDIT:
It appears that the OLE DB driver may be the culprit.
When I change to use the Native Client, it appears to work correctly.
SQL2008_ConnectionString = "Driver={SQL Server Native Client 10.0};Server=<SQL2008ServerName>;UID=<UserName>;pwd=<Password>;Database=<DataBaseName>;"
As this is a heavily used legacy app, and regression testing everything to use a new driver is time prohibitive. Is there any way to make the OLE DB driver do the correct thing?
3rd EDIT:
Just realized it is not a SQL 2008 R2 box. I was mistaken. It is just SQL2008
Here is my ##VERSION:
Microsoft SQL Server 2008 (SP3) - 10.0.5500.0 (X64) Sep 21 2011 22:45:45 Copyright (c) 1988-2008 Microsoft Corporation Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1) (VM)
I found the solution.
Apparently the solution is to set the precision and numeric scale on the command object parameter to that of the defined size of addbTimeStamp.
Adding these two lines to the cmd object parameter before the call to the SQL2008 database, and the seconds are passed to the stored procedure.
.Parameters("#dtDateAndTime").Precision = 23
.Parameters("#dtDateAndTime").NumericScale = 3

Access 2010 ADO on Windows XP Mode (in ADDE format)

I have a problem with ADO in My application. I have Access installed on my computer with Win7Pro and there I can use both version (ACCDB and ACCDE). But only ACCDB works under runtime (with SP1) in WinXPMode environment.
There is the code
Dim strSQL As String, Cnxn As ADODB.Connection, Rsxn As ADODB.Recordset
Dim lngDummy As Long
lngCount = DCount("[Sklad]", "cisSklad", "[Zobrazit]")
CountData = lngCount
If CountData = 0 Then Exit Sub
ReDim ItemValues(lngCount - 1)
Set Cnxn = CurrentProject.AccessConnection
Set Rsxn = New ADODB.Recordset
...
In ACCDE (under RunTime on XPMode):
The line Set Cnxn = CurrentProject.AccessConnection return the message Error 13: Type mismatch.
I have the reference to ADO 2.8.
Debug.Print CurrentProject.AccessConnection: Provider=Microsoft.Access.OLEDB.10.0;Persist Security Info=False;Data Source=C:\Work\SkladII\Sklad.accde;User=Admin;Data Provider=Microsoft.ACE.OLEDB.12.0
All tables in sklad.accde are linked
Do you have any idea, where is the problem?
Investigate whether this issue is confined to early binding for ADO in WinXPMode. Remove the reference for ADO and revise your code to use late binding.
Dim strSQL As String, Cnxn As Object, Rsxn As Object
Set Cnxn = CurrentProject.Connection
'Set Rsxn = New ADODB.Recordset
Set Rsxn = CreateObject("ADODB.Recordset")

How to execute stored procedure from Access using linked tables

I have an Access 2003 database that connects to a SQL Server 2008 box via ODBC. The tables from SQL Server are connected as linked tables in Access. I have a stored procedure on the SQL Server that I am trying to execute via ADO code. The problem I have is that Access cannot seem to find the procedure. What do I have to do within Access to be able to execute this stored procedure? Some facts ...
The stored procedure in question accepts one parameter which is an integer. The stored procedure returns a recordset which I am hoping to use as the datasource for a ListBox.
Here is my ADO code in Access ...
Private Sub LoadUserCaseList(userID As Integer)
Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
cmd.ActiveConnection = CurrentProject.Connection
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "uspGetUserCaseSummaryList"
Dim par As New ADODB.Parameter
Set par = cmd.CreateParameter("userID", adInteger)
cmd.Parameters.Append par
cmd.Parameters("userID") = userID
Dim rs As ADODB.Recordset
Set rs = cmd.Execute()
lstUserCases.Recordset = rs
End Sub
The error I get is "the microsoft jet database engine cannot find the input table or query "uspGetUserCaseSummaryList".
CurrentProject.Connection is the connection to your Access database. You can verify that by doing this in the Immediate window:
Debug.Print CurrentProject.Connection
You need to create a new ADODB.Connection object with a connection string which points to your SQL Server instance. Have your ADODB.Command object use that connection.
Edit: You can eliminate the ADODB.Command object, and use the Execute method of the connection to return records from your stored procedure. This example uses a stored procedure which expects 3 parameters.
Private Sub GetCenterCodes()
Dim cnn As ADODB.Connection
Dim rs As ADODB.Recordset
Set cnn = New ADODB.Connection
cnn.ConnectionString = "Provider=SQLOLEDB;Data Source=VM2003\sqlexpress;" _
& "User ID=foo;Password=bar;Initial Catalog=Inventory"
cnn.Open
Set rs = New ADODB.Recordset
Set rs = cnn.Execute("EXEC uspGetCenterCodes 14, 14, 501")
Debug.Print rs(0), rs(1), rs(2)
rs.Close
Set rs = Nothing
cnn.Close
Set cnn = Nothing
End Sub
You can find a connection string example which matches your needs at ConnectionStrings.com