two things:
first: I have googled everywhere, including stackoverflow. Just about questions regarding sql vs vb6 are about connection string. I have this down pat. Any reference to mysql queries are for the query itself - but not in tangent with vb6 or any language
second: I am very proficient in PHP/MySQL so that aspect of help I am not seeking.
what I am stuck on, is how vb6 handles sql queries a little (lot) different than php. So once I get connected, how to I tell vb6 to look up a field.
php version
$sql = "SELECT * FROM table field = data where something = that";
$query = mysql_query($sql) or die("bad query: <br>$sql<br>".mysql_error());
then either use a fetch array or work with this.
how is this accomplished in vb6?
I saw some source referring to rdoQry. Can someone shed some light on this with example code? I don ont need the connection part. have that set.
my connection is this:
Dim cnMySql As New rdoConnection
cnMySql.CursorDriver = rdUseOdbc
cnMySql.Connect = "uid=root;pwd=root;" _
& "server=127.0.0.1;" _
& "driver={MySQL ODBC 3.51 Driver};" _
& "database=mydatabase;dsn=;"
cnMySql.EstablishConnection
works perfect.
ADO is the successor to RDO. I use code similar to this to query MySQL from Visual Basic using ADO.
Dim conn As New ADODB.Connection
conn.Open "connection string"
Dim cmd As New ADODB.Command
With cmd
.ActiveConnection = conConnection
.CommandText = "SELECT fields FROM table WHERE condition = ?"
.CommandType = adCmdText
End With
Dim param As New ADODB.Parameter
Set param = cmd.CreateParameter("condition", adVarChar, adParamInput, 5, "value")
cmd.Parameters.Append p
Dim rs As New ADODB.Recordset
rs.CursorLocation = adUseClient
rs.Open cmd, , adOpenStatic, adLockOptimistic
Dim temp
Do While Not rs.EOF
temp = rs("field")
rs.MoveNext
Loop
rs.Close
conn.Close
Typically, with VB6 (gosh, are people still using this??) you would connect to a database using ADO. ADO is a common database class which allows you to use the same syntax for any database.
The connection code you've provided is using RDO, which is a predecessor to ADO (and since VB6/ADO is pretty old now, that means RDO is historic). For your purposes, the two should work fairly similarly, but I'd suggest switching to ADO now if you have a chance, before you've written too much code.
This thread seems to be pointing someone else in the right direction in writing the connection code: http://www.vbforums.com/showthread.php?t=654819
Once you've got a connection, you need to run your queries. The process for this should make sense if you're used to querying from PHP; it's basically the same process, although you typically need to mess around with configuring a few more options than with PHP. It would look something like this:
Set rs = New ADODB.Recordset
rs.ActiveConnection = adoconn
rs.CursorLocation = adUseClient
rs.CursorType = adOpenDynamic
rs.LockType = adLockOptimistic
rs.Open "SELECT blah blah blah"
While Not rs.EOF
Text1.Text = rs("Name")
rs.MoveNext
Wend
rs.Close
Hope that helps.
Related
I've run across this error when attempting to query the database with ADO. From searching around I've found that this probably means there is an issue with the SQL that I am using.
Dim rs As Object
Dim varGetRows As Variant
Dim sqlStr As String
sqlStr = "SELECT qryEmpRewardsDetail.PBRID, qryEmpRewardsDetail.ActualReward, qryEmpRewardsDetail.ProratedActual, qryEmpRewardsDetail.Adjust, qryEmpRewardsDetail.Total, qryEmpRewardsDetail.Prorated FROM qryEmpRewardsDetail WHERE qryEmpRewardsDetail.ReviewYearID=8 AND qryEmpRewardsDetail.EmployeeID=30 AND qryEmpRewardsDetail.TypeID=1;"
Set rs = CreateObject("ADODB.Recordset")
rs.Open sqlStr, CurrentProject.Connection
varGetRows = rs.GetRows()
I've re-written it in a couple of different ways, checked the spelling a hundred times and copied and pasted it into an access query which ran fine.
For the life of me I can't figure out what could be wrong with it. Any ideas on what it could be or some suggestions on how to narrow down the issue?
Thanks!
Does this run?
SELECT * FROM qryEmpRewardsDetail WHERE qryEmpRewardsDetail.ReviewYearID=8 AND qryEmpRewardsDetail.EmployeeID=30 AND qryEmpRewardsDetail.TypeID=1
If it does, then you likely spelt a field wrong, add one by one till happy.
Otherwise, try removing each WHERE condition and test between each.
Define your recordset fully just to be safe:
Dim rst As ADODB.Recordset
Set rst = New ADODB.Recordset
rst.ActiveConnection = CurrentProject.Connection
rst.CursorType = adOpenDynamic
rst.LockType = adLockReadOnly
rst.Open sqlStr
If rst.BOF and rst.EOF Then
'no records returned
End If
Do While Not rst.EOF
'Doing stuff with row
rst.MoveNext
Loop
Please can somebody help me with this problem.
I have a Form in VBA and from this from I want to run some SQL queries and retrieve the data from my database and then place the result in a Text box in the Form(GUI)
I have about 20 tables in my Database but surprisingly to me I am only able to access the first table (InventoryCompleteList).
Every attempt to access another table returns an error saying for example (Invalidobject name 'functionalTestResults') whereas when I run the query for (inventoryCompleteList), it seems to be working. Note functionalTestResults and inventoryCompleteList are both tables in my sql server
Please can anyone help me figure out what the problem might be.
Below is the view of my DB
`Private Sub ENTER_Click()
Dim cn As Object
Dim rs As Object
Dim strFile As String
Dim strCon As String
Dim strSQL, strInput As String
strCon = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security
Info=True;Initial Catalog=KBOW;Data Source=10.23.30.8\KBOW;Use Procedure
for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation
ID=ULWW101;Use Encryption for Data=False;Tag with column collation when
possible=False;"
Set cn = CreateObject("ADODB.Connection")
cn.Open strCon
strSQL = "SELECT Date,Location FROM functionalTestResults;"
'Added the following four lines
Set rs = CreateObject("ADODB.RECORDSET")
rs.ActiveConnection = cn
rs.Open strSQL
Sheet1.Range("A1").CopyFromRecordset rs
Result.Text = "CopyFromRecordset rs"
'removed
'cn.Execute strSQL
rs.Close
cn.Close
Set cn = Nothing
End Sub
`
You need to be granted "Select" on those tables, as it seems you currently do not have this permission.
Speak with your dba about being granted access to this table.
Im trying to insert a row in a mysql db using Excel Macros. The connection appears to be working OK but i get a vba 3001 error
(Microsoft visual basic 3001 arguments are of the wrong type, or are out of acceptable range, or are in conflict with one another)
when y execute this code:
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
ConnectDB
'strSQL = "INSERT INTO talar.ots (UbicacionTecnica, Equipo, Posmant) VALUES ('sdasd', 'sdasd','sdasd')"
rs.Open strSQL, oConn, adOpenDynamic, adLockOptimistic
I allready read and try different things with 50 tutorials and other posts in this page, all bad results....
this is the code of the connection:
Private Sub ConnectDB()
Dim oConn As ADODB.Connection
Set oConn = New ADODB.Connection
oConn.Open "DRIVER={MySQL ODBC 5.2 Unicode Driver};" & _
"SERVER=localhost;" & _
"DATABASE=talar;" & _
"USER=root;" & _
"PASSWORD=root;" & _
"Option=3"
End Sub
MySQL ODBC 5.2 Unicode Driver is installed, mysql service is running fine, I am using Excel 2010, windows 7. I dont know if this information is enough.
anyone have any idea?
thanks!
oConn is local to the ConnectDB sub so you are passing nothing to the recordsets Open.
Add Option Explicit to the top of your code file to receive a warning when you do something like this.
Make a function that returns the connection:
Private Function ConnectDB() As ADODB.Connection
Set ConnectDB = New ADODB.Connection
ConnectDB.Open "DRIVER={MySQL ODBC 5.2 Unicode Driver};SERVER=localhost;DATABASE=talar;USER=root;PASSWORD=root;Option=3"
End Function
Then
dim cn as ADODB.Connection
set cn = ConnectDB()
cn.Execute "INSERT INTO talar.ots (UbicacionTecnica, Equipo, Posmant) VALUES ('sdasd', 'sdasd','sdasd')"
cn.Close
You do not need a Recordset for an insert as no rows will be returned.
When you do need a Recordset adOpenForwardOnly, adLockReadOnly are better than adOpenDynamic, adLockOptimistic unless you specifically need the features offered by the latter.
I am trying to make an Update to a Passthrough query using MS Access to an ODBC server that I have no control over. The reason I have to use a Passthrough is that the records I am accessing have more than 255 fields (I would use a linked table if I could).
I've been using this resource to get the data using Passthrough (http://www.techonthenet.com/access/tutorials/passthrough/basics09.php)
The query is simply: SELECT FullName, PointNumber FROM DNP3.CDNP3AnalogIn
The ODBC Connect Str is: ODBC;DSN=SCX6_DB;LOCATION=Main;UID=admin;PWD=password;LOCALTIME=False;
Now inside an Access Database I have a table (SCADA DB Tags) with same name for the Fields (FullName, PointNumber), and I want to update the fields inside the ODBC Database using an Update Passthrough query, but I am unsure how to do this.
I saved the previous Query as DNP3_CDNP3AnalogIn Query, and tried to make a new Query:
UPDATE [DNP3_CDNP3AnalogIn Query] INNER JOIN [SCADA DB Tags] ON
[DNP3_CDNP3AnalogInQuery].FullName = [SCADA DB Tags].FullName
SET [DNP3_CDNP3AnalogIn Query].[PointNumber] = [SCADA DB Tags].[PointNumber];
But I get an error from Access: Operation must use an updateable query.
I know there is someway to do this but I can't seem to find an example (I might not be googling the correct phrase). Microsoft page (http://technet.microsoft.com/en-us/library/bb188204%28v=sql.90%29.aspx) says: There is, however, one important limitation: the results returned by SQL pass-through queries are always read-only. If you want to enable users to perform updates based on the data retrieved, you must write code to handle this. Unfortunately it doesn't give an example to do it!
Can anyone give me a solution, I can use VBA if required? I can also give more background if required. Unfortunately I'm not an expert in Access, I'm just trying to come up with an automated solution that could save me some time.
When they said that "If you want to enable users to perform updates based on the data retrieved [from a pass-through query], you must write code to handle this" they probably meant something like this:
Option Compare Database
Option Explicit
Public Sub UpdateSqlServer()
Dim cdb As DAO.Database, rst As DAO.Recordset
Dim con As Object ' ADODB.Connection
Dim cmd As Object ' ADODB.Command
Const adParamInput = 1
Const adInteger = 3
Const adVarWChar = 202
Set cdb = CurrentDb
Set rst = cdb.OpenRecordset( _
"SELECT " & _
"[SCADA DB Tags].FullName, " & _
"[SCADA DB Tags].PointNumber " & _
"FROM " & _
"[DNP3_CDNP3AnalogIn Query] " & _
"INNER JOIN " & _
"[SCADA DB Tags] " & _
"ON [DNP3_CDNP3AnalogIn Query].FullName = [SCADA DB Tags].FullName", _
dbOpenSnapshot)
Set con = CreateObject("ADODB.Connection")
con.Open "DSN=SCX6_DB;"
Set cmd = CreateObject("ADODB.Command")
cmd.ActiveConnection = con
cmd.CommandText = _
"UPDATE DNP3.CDNP3AnalogIn SET " & _
"PointNumber=? " & _
"WHERE FullName=?"
cmd.Parameters.Append cmd.CreateParameter("?", adInteger, adParamInput) ' PointNumber
cmd.Parameters.Append cmd.CreateParameter("?", adVarWChar, adParamInput, 255) ' FullName
cmd.Prepared = True
Do Until rst.EOF
cmd.Parameters(0).Value = rst!PointNumber
cmd.Parameters(1).Value = rst!FullName
cmd.Execute
rst.MoveNext
Loop
Set cmd = Nothing
con.Close
Set con = Nothing
rst.Close
Set rst = Nothing
Set cdb = Nothing
End Sub
Notes:
The code uses your existing ODBC DNS.
It uses a Prepared Statement to perform the updates, increasing efficiency and protecting against failures related to SQL Injection.
The source Recordset performs an INNER JOIN on the pass-through query to ensure that the code only tries to update rows on the server that actually exist on the server.
Are you saying that [DNP3_CDNP3AnalogIn Query] is server side based and that table [SCADA DB Tags] is local based? In that case you cannot use a pass-through query.
However since the tables ARE in different locations pass-though cannot touch BOTH at the same time.
You can however execute "single" server side (pass-though) in a loop. If you setup a pass-though query and SAVE it, then this code will work:
Dim qdfPass As DAO.QueryDef
Dim rstLocal As DAO.Recordset
Dim strSQL As String
Dim strSQL2 As String
Set qdfPass = CurrentDb.QueryDefs("MyPass")
strSQL = "UPDATE [DNP3_CDNP3AnalogIn Query] " & _
"SET [DNP3_CDNP3AnalogIn Query].[PointNumber] = 'xxxx' " & _
"WHERE [DNP3_CDNP3AnalogInQuery].FullName = 'zzzz' "
Set rstLocal = CurrentDb.OpenRecordset("[SCADA DB Tags]")
Do While rstLocal.EOF = False
strSQL2 = Replace(strSQL, "xxxx", rstLocal!PointNumber)
strSQL2 = Replace(strSQL2, "zzzz", rstLocal!FullName)
qdfPass.SQL = strSQL2
qdfPass.Execute
rstLocal.MoveNext
Loop
rstLocal.Close
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