I'm retrieving Data from a Database in a record set using VB6... so while retrieving data using Select in SQL I added a column called Comments along wit it so that in the recordset, all the columns of the table+'Comments' column would be present... I don't want to(and also I cannot) update any contents in the database as i'm only 'fetching' data frm the database now...
Now when i pass the fetched data for validation, I want to fill the 'comments' Column with the respective errors if the particular row in the recordSet is erroneous).... When i do that i get an error saying "I'm not authorized to do that!!(to update the 'Comments' Column"....
Now My Question is "In what way i can solve this problem???".. I tried to replicate this recordset and there by now filling the 'comments'column (in the replicated one) which in turn showed the same error... It seems this could be because the duplicate one(recordSet) just retains the properties of the original one...
Can u any1 help how to solve this???? Any ways to replicate the recordset(without inheriting its properties something)??????
I think you are just asking how to do a disconnected recordset.
For that you just change the cursor location of the recordset.
Dim rstTest as ADODB.RecordSet
Set rstTest = New ADODB.RecordSet
With rstTest
.CursorLocation = adUseClient
.Open "your sql here", your_connection_object, adOpenStatic, adLockBatchOptimistic, adCmdText
' now disconnect it and force the local copy
.ActiveConnection = Nothing
End With
Not exactly what you are looking for, but this is how I do it:
Create a class to encapsulate the recordset ('Customer' class for 'Customer' table)
Add your Comment property to the class and not to recordset
Add a Validate method to your class. Have it write to your Comment property (I use an Errors Collection)
Read the recordset
Parse it into a "new Customer"
Validate
Check the Comment property (or the Errors Collection)
You can use the MSDataShape with its SHAPE..APPEND syntax to append a new Field to an ADO Recordset. Here's a quick example using Jet (a.k.a. MS Access):
Sub ShapeAppendField()
On Error Resume Next
Kill Environ$("temp") & "\DropMe.mdb"
On Error GoTo 0
Dim cat
Set cat = CreateObject("ADOX.Catalog")
With cat
.Create _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & _
Environ$("temp") & "\DropMe.mdb"
Dim jeng
Set jeng = CreateObject("JRO.JetEngine")
jeng.RefreshCache .ActiveConnection
Set .ActiveConnection = Nothing
End With
Dim con
Set con = CreateObject("ADODB.Connection")
With con
.ConnectionString = _
"Provider=MSDataShape;" & _
"Data Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & _
Environ$("temp") & "\DropMe.mdb"
.CursorLocation = 3
.Open
.Execute _
"CREATE TABLE Test (" & _
"existing_col INTEGER NOT NULL);"
.Execute _
"INSERT INTO Test (existing_col)" & _
" VALUES (1);"
Dim rs
Set rs = CreateObject("ADODB.Recordset")
With rs
.CursorType = 2
.LockType = 4
.Source = _
"SHAPE {" & _
" SELECT existing_col" & _
" FROM Test" & _
"} APPEND NEW adInteger AS new_col"
Set .ActiveConnection = con
.Open
Set .ActiveConnection = Nothing
.Fields("new_col").value = 55
MsgBox .GetString
.Close
End With
End With
End Sub
Related
Debugger returns automation error when running the following :
Private Sub setDB()
Dim SQL As String
Dim Var As String
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
conn.Open "DRIVER={MariaDB ODBC 3.0 Driver}" _
& ";SERVER=" & "localhost" _
& ";DATABASE=" & "pbx" _
& ";USER=" & "root" _
& ";PASSWORD=" & "r00t" _
Var = Worksheets(3).Range("B2").Value
SQL = "UPDATE ps_product SET ean13='" & Var & "' WHERE id_product=12"
conn.Execute (SQL)
However when I assign a value to Var like this: Var=10, the code runs fine. Am I missing something here? I have searched on the internet for several days and I didn't find anything similar. Can some1 help or maybe send a link to a similar issue, please?
Consider parameterization, the preferred method to bind application layer values to executed SQL queries. ADO supports this approach with Command parameters. This avoids messy concatenation, quote punctation, and escape needs if string value contains special characters like single quotes.
Dim Sql As String, Var As String
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command ' NEW OBJECT TO INITIALIZE
Set conn = New ADODB.Connection
conn.Open "DRIVER={MariaDB ODBC 3.0 Driver}" _
& ";SERVER=" & "localhost" _
& ";DATABASE=" & "pbx" _
& ";USER=" & "root" _
& ";PASSWORD=" & "r00t" _
' PREPARED STATEMENT WITH PLACEHOLDER (NO QUOTES OR CONCATENATION)
Sql = "UPDATE ps_product SET ean13=? WHERE id_product=12"
' CONVERT TO NEEDED TYPE
Var = CStr(Worksheets(3).Range("B2").Value)
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = conn
.CommandText = Sql
.CommandType = adCmdText
' BIND PARAMS AND DEFINE TYPE AND LENGTH
.Parameters.Append .CreateParameter("prm", adVarChar, adParamInput, 255, Var)
' EXECUTE ACTION
.Execute
End cmd
The query is working when the desired cell is passed as a parameter. (Thx to #Parfait for the hint)
Some useful info which helped me figure this out can be found here:
VBA, ADO.Connection and query parameters
https://learn.microsoft.com/en-us/sql/ado/guide/data/creating-and-executing-a-simple-command?view=sql-server-ver15
https://learn.microsoft.com/en-us/sql/ado/guide/data/passing-parameters-to-a-named-command?view=sql-server-ver15
Working example:
Private Sub setDB()
Dim Cm As New ADODB.Command
Dim Rs As New ADODB.Recordset
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection
Test = Worksheets(3).Range("B2").Value
CommandText = "UPDATE ps_product SET ean13=? WHERE id_product=12;"
conn.Open "DRIVER={MariaDB ODBC 3.0 Driver}" _
& ";SERVER=" & "localhost" _
& ";DATABASE=" & "pbx" _
& ";USER=" & "root" _
& ";PASSWORD=" & "r00t" _
Cm.CommandText = CommandText
Cm.CommandType = adCmdText
Cm.Name = "Var"
Set Cm.ActiveConnection = conn
conn.Var Test, Rs
End Sub
Disclaimer: I am new to VBA.
I hope to pass the value in the SQL query (30881570) through a field on my Excel sheet. I have tried a few different things.
Private Sub cmdImport_Click()
Call cmdClear_Click
Dim conn As New ADODB.Connection, cmd As New ADODB.Command, rs As New ADODB.Recordset
With conn
.ConnectionString = _
"Provider=SQLOLEDB; " & _
"Data Source=PRGTAPPDBSWC019; " & _
"Initial Catalog=DETEP;" & _
"Integrated Security=SSPI;"
.Open
End With
With cmd
.ActiveConnection = conn
.CommandText = "SELECT * FROM [dbo].[tbl_PMHeader] WHERE [PMHeader_PM_NUM] = '30881570'"
.CommandType = adCmdText
End With
Set rs.Source = cmd
rs.Open
'Need this to populate header row, starting at specified Range
For intColIndex = 0 To rs.Fields.Count - 1
Range("B1").Offset(0, intColIndex).Value = rs.Fields(intColIndex).Name
Next
'This is where your data table will be copied to
ActiveSheet.Range("B2").CopyFromRecordset rs
Worksheets("Sheet1").Columns("B:BB").AutoFit
Worksheets("Sheet1").Range("A25").Formula = "=COUNTA(B:B)-1"
End Sub
It looks like you're already passing that value as criteria for the query's WHERE statement.
If you're asking how to replace that with a value from a worksheet, here's one way:
.CommandText = "SELECT * FROM [dbo].[tbl_PMHeader] " & _
"WHERE [PMHeader_PM_NUM] = '" & Sheets("mySheet").Range("A1") & "'"
...where your worksheet is named mySheet and the value is in cell A1.
This is the simplest method, potentially fine for internal use by trusted parties, but if the value has any ' single-quotes in it, you will get an error.
Worst-case scenario, this method leaves you open to SQL Injection attacks. Depends on your needs (and whether this this is just a school assignment), you may be better of using a parameter query.
See Also:
MSDN Blog : How and Why to Use Parameterized Queries
MSDN Blog : Everything About Using Parameters from Code
Private Sub cmdImport_Click()
Dim conn As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim rs As New ADODB.Recordset
Dim sqlStr As String
With conn
.ConnectionString = _
"Provider=SQLOLEDB; " & _
"Data Source=PRGTAPPDBSWC019; " & _
"Initial Catalog=DETEP;" & _
"Integrated Security=SSPI;"
.Open
End With
orderno = Sheets("Sheet1").Range("A22")
strSql = "SELECT * FROM [dbo].[tbl_PMHeader] " & _
"WHERE [PMHeader_PM_NUM] = " & orderno
With cmd
.ActiveConnection = conn
.CommandText = strSql
.CommandType = adCmdText
End With
'Call cmdClear_Click
Set rs.Source = cmd
rs.Open
'Need this to populate header row, starting at specified Range
For intColIndex = 0 To rs.Fields.Count - 1
Range("B1").Offset(0, intColIndex).Value = rs.Fields(intColIndex).Name
Next
'This is where your data table will be copied to
ActiveSheet.Range("B2").CopyFromRecordset rs
Worksheets("Sheet1").Columns("B:BB").AutoFit
Worksheets("Sheet1").Range("A25").Formula = "=COUNTA(B:B)-1"
End Sub
I am trying to import a CSV file split by semicolon ";" into an excel object so I can use it later on.
Ideally i would like to use ADO, DAO or ADODB so I can also run SQL queries on the object, and get sum of specific fields, or total number of fields and so on.
So far i've gotten the code below, but it does not split the data by ";", so it all comes back as 1 field instead of multiple fields that can be handled.
Sub Import()
Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim f As ADODB.Field
Dim csvName, csvPath
csvPath = ActiveWorkbook.path
csvName = "fileName.csv"
conn.Open "DRIVER={Microsoft Text Driver (*.txt; *.csv)};DBQ=" & csvPath & ";"
rs.Open "SELECT * FROM " & csvName, conn, adOpenStatic, adLockReadOnly, adCmdText
Debug.Print rs.Fields
While Not rs.EOF
For Each f In rs.Fields
Debug.Print f.Name & "=" & f.Value
Next
Wend
End Sub
Can anyone give me an idea how I can also split the data by ";" and query it using SQL query? Or a different object that I could load a CSV into and query certain columns.
Here's example:
Public Sub QueryTextFile()
Dim rsData As ADODB.Recordset
Dim sConnect As String
Dim sSQL As String
' Create the connection string.
sConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Files\;" & _
"Extended Properties=Text;"
' Create the SQL statement.
sSQL = "SELECT * FROM Sales.csv;"
Set rsData = New ADODB.Recordset
rsData.Open sSQL, sConnect, adOpenForwardOnly, _
adLockReadOnly, adCmdText
' Check to make sure we received data.
If Not rsData.EOF Then
' Dump the returned data onto Sheet1.
Sheet1.Range("A1").CopyFromRecordset rsData
Else
MsgBox "No records returned.", vbCritical
End If
' Clean up our Recordset object.
rsData.Close
Set rsData = Nothing
End Sub
The only answer I found that was usable was to create an ini file in the current folder, and enter the delimiter in the ini file.
iniPath = activeworkbook.path & "\"
iniName = "schema.ini"
iniPathName = iniPath & iniName
If Not fso.FileExists(iniPathName) Then
fso.CreateTextFile (iniPathName)
End if
Here is my code, I'm in using VBA. I get no errors, the task is added to the sharepoint list, but the Assigned To field is blank.
I have also listed all the fields in the recordset and there is no Assignment field available. I noticed some unanswered questions on the web about how to query the value of a lookup field.
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;WSS;IMEX=0;RetrieveIds=Yes;" & _
"DATABASE=" & sSHAREPOINT_SITE & ";" & _
"LIST=" & sTASK_LIST_GUID & ";"
' Create some new objects.
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open the connection.
With cn
.ConnectionString = sConn
.Open
End With
sSQL = "SELECT * FROM [Tasks] as tbl;"
' Open up the recordset.
rs.Open sSQL, cn, adOpenStatic, adLockOptimistic
With rs
.AddNew
![Task Name] = "test"
AssignedTo = "SomeEmailAddress"
![Categories] = "Data Requests"
.Update
End With
rs.Close
I do know how to do this if I "connect with Outlook", but I was trying to avoid all that.
The value would have to be in the format of LookupId;#LookupValue
Where LookupId is the user's ID for that particular site and the LookupValue is the users Display Name
So you would have:
AssignedTo = "48;#Chris McKay"
I want to connect to a MS SQL Server database using an Outlook macro. But I don't know if the code is wrong or I need to add a library/driver or what happens here but it doesn't work.
Private Sub Application_Startup()
On Error GoTo ExitHere
'adodb connection to other database
stg_cn.Open "Provider = SQLOLEDB;" & _
"Data Source = 192.168.100.100;" & _
"Initial Catalog = hugeDB;" & _
"Integrated Security=SSPI;" & _
"User ID = oneuser;" & _
"Password = onepassword;"
sQuery = "SELECT * FROM documents where location = 'IE'"
'set reference to query
Set cmd = New ADODB.Command
cmd.ActiveConnection = stg_cn
cmd.CommandType = adCmdText
cmd.CommandText = sQuery
Set rs = cmd.Execute
Do While Not rs.EOF
For i = 0 To rs.Fields.count - 1
MsgBox (i + 1)
Next
rs.MoveNext
Loop
ExitHere:
If Not stg_cn Is Nothing Then stg_cn.Close
Set rs = Nothing
Set stg_cn = Nothing
Exit Sub
End Sub
On eye-test I am not able to figure out whats wrong, I think it has to do something with the way you are doing the ADO operations.
But I am just putting up the last macro I wrote to connect to SQL-Server from Macro. Hope it helps.
Private Sub Workbook_Open()
On Error GoTo ErrorHandler
'**************************************Initialize Variables**************************************
sServer = "<SQL SERVER Server>"
sDBName = "<SQL SERVER DB>"
'**************************************Open Connection**************************************
'adodb connection to other database
stg_cn.Open "Provider=SQLOLEDB;Data Source=" & sServer & _
";Initial Catalog=" & sDBName & _
";Integrated Security=SSPI;"
sQuery = "SELECT * " & _
"FROM Table "
'set reference to query
Set cmd = New ADODB.Command
cmd.ActiveConnection = stg_cn
cmd.CommandType = adCmdText
cmd.CommandText = sQuery
Set rs = cmd.Execute
Do While Not rs.EOF
For i = 0 To rs.Fields.Count - 1
<PERFORM OPERATIONS>
Next
rs.MoveNext
Loop
ExitHere:
If Not stg_cn Is Nothing Then stg_cn.Close
Set rs = Nothing
Set stg_cn = Nothing
Exit Sub
End Sub
The connection string #CodePhobia has provided should work for you.
The below just includes User ID and Password functionality, as your original question showed trying to connect using this.
Dim rsConn as ADODB.Connection
Set rsConn = New ADODB.Connection
With rsConn
.ConnectionString = "Provider = sqloledb;" & _
"Data Source = myServerName;" & _
"Initial Catalog = myCatalog;" & _
"Integrated Security=SSPI;" & _
"User ID = myUserID;" & _
"Password = myPassword;"
.Open
End With
You can use this website to find connection strings in the future. It should cover all possible connections you wish to establish.