VBA(AUTOCAD) SQL query to store String Values - sql

I have a small issue, I am trying to code a Macro for Autocad in VBA.
I am trying to read a certain column value through sending a SQL native query that connects to the database server.
The problem is that my String variable descToReturn that's going to hold a value of that column is returning null. I can't seem to figure out where I am wrong. So if anyone can advise that'd be great.
Here's the code below:
Private Sub btnDuplicate_Click()
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
Dim BOMLineToCheck As AcadBlockReference
Dim BOMAttributes As Variant
Dim partNoToCheck As String
Dim i As Integer
Dim descToReturn As String
ConnectionString = "Provider=SQLxxxxx.1;Password=xxxx;Persist Security Info=True;User ID=xxxx;Data Source=xx\xx;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=xxx_xxx"
Set cnn = New ADODB.Connection
cnn.ConnectionString = ConnectionString
cnn.Open
'cnn.CommandTimeout = 900
Set rst = New ADODB.Recordset
StrQuery = "SELECT * FROM [My Table Name] WHERE [My Column]='partNoToCheck'"
For Each BOMLineToCheck In ThisDrawing.ModelSpace
If BOMLineToCheck.Name = "BOM3LINE_old" Then
BOMAttributes = BOMLineToCheck.GetAttributes()
For i = 0 To UBound(BOMAttributes)
If BOMAttributes(i).TagString = "PART#" Then
partNoToCheck = BOMAttributes(i).TextString
End If
Next i
End If
rst.Open StrQuery, cnn, adOpenDynamic
With rst
If Not .EOF Then
descToReturn = rst![My Coulmn]
End If
End With
rst.Close
MsgBox descToReturn
Next
End Sub

Look closely for a typo:
descToReturn = rst![My Coulmn]
You probably mean:
descToReturn = rst![My Column]
See the difference?

So, I found the answer, because I am bringing SQL within VBA environment, the syntax was not right and its a weird syntax:
correct Syntax for SQL query:
StrQuery = "SELECT * FROM [My Table] WHERE [My Column]= '" & partNoToCheck & "'"

Related

Get max value from Access database using SQL

I need to get the max value from a column and store it at long varibale.
My VBA code :
Private Sub ADOFromExcelToAccessDstribute()
Dim dstibute_ID As Long
' get the next dstibute id
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim qry As String
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=W:\data\Database.accdb;jet
OLEDB:Database password=123;"
qry = "SELECT Max(distributeSummeryTable.distributeID) AS MaxOfdistributeID FROM
distributeSummeryTable;"
rst.Open qry, cnn, adOpenKeyset, adLockOptimistic
dstibute_ID = rst.MaxOfdistributeID
rst.Close
cnn.Close
'buile the export log
exportReportPacks
If (dstibute_ID = "" Or dstibute_ID = 0) Then
dstibute_ID = 1
End If
'add data to data base
ADOFromExcelToAccessDstributeSummeryTable (dstibute_ID)
ADOFromExcelToAccessFulldistributeSummeryTable (dstibute_ID)
End Sub
This is my database table and the field I want to return
I get an error in my code.
Info online and at StackOverflow didn't solve my issue.
SOLVED,
my syntax was wrong i should use ! insted of .
i try to store null value in long, it make error.
my change was :
If (rst!MaxOfdistributeID <> "") Then
dstibute_ID = rst!MaxOfdistributeID
End If

Is there a limit to the query length being passed to ADODB?

I am currently testing a framework that stores a SQL query in a cell on an excel workbook and then passes the cell value to a variable. This variable then gets executed through rs.Open query, cn where:
Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
and I have tried these for "query" :
Dim query as String
Dim query as Variant
or even playing with fixed length queries:
Dim query as String * 9999
In playing with the output of the query string, it cuts off somewhere around 8000. Google is coming up short for me, so I am coming here for answers. Is there a specific limit to what a variable can pass to recordset.Open()?
NB: The connection string I am using for this particular query is :
ConnectionString = "User ID=User;Password=PW;Data Source=DB;Provider=OraOLEDB.Oracle"
But if you know whether there is a system specific limit for Oracle, NetezzaSQL, or MS SQL Server (SQLOLEDB.1) please let me know. I will need to specify the limitations of each in order to define which new queries will need to be converted into stored procedures.
Here is the essentials of the code:
Sub RunQueryTable()
Dim cn As ADODB.Connection
Dim RS As ADODB.Recordset
Dim iCols As Integer
Dim DB As String, User As String, PW As String
Dim SQLTable As Worksheet
Dim ConnectionString as String
Dim query As String 'Or Dim query As Variant 'Or Dim query As String * 9999
Dim i As Long
etc, etc.
Set SQLTable = Sheet32
Set cn = New ADODB.Connection
Set RS = New ADODB.Recordset
DB = _____
User = ______
PW = ____
ConnectionString = "User ID=" & User & _
";Password=" & PW & _
";Data Source=" & DB & _
";Provider=OraOLEDB.Oracle"
query = SQLTable.Cells(i, 3).Text
cn.Open (ConnectionString)
RS.CursorType = adOpenForwardOnly
RS.Open (query), cn
For iCols = 0 To RS.Fields.count - 1
Worksheets("Output").Cells(1, iCols + 1).Value = RS.Fields(iCols).Name
Next
Worksheets("Output").Cells(2, "A").CopyFromRecordset RS
RS.Close
cn.Close
End Sub
The specific error I am getting from VBA is : "ORA-00923: FROM keyword not found where expected" because the query is getting cut off.
Here's your problem:
query = SQLTable.Cells(i, 3).Text
Consider:
Range("A1").Value=string(12000,"*")
? len(range("a1").value) '>> 12000
? len(range("a1").text) '>> 8221

ADODB Recordset.Open giving syntax error excel to SQL

I'm toast, cannot figure out why I'm getting a SYNTAX error on the line
rst.Open strSQL
I've tried it with rst.Open strSQL, cnt, adOpenStatic, adLockReadOnly, adCmdText
But it still gives me an error.
I have a sneaking suspicion it has to do with how strSQL is taking a cell value and appending it to the end of a string.
Any help is highly appreciated.
Public Sub EzPz()
Dim cnt As ADODB.Connection
Dim rst As ADODB.Recordset
Set cnt = New ADODB.Connection
Set rst = New ADODB.Recordset
Dim strSQL As String
'Open connection
cnt.ConnectionString = "Driver={SQL Server};Server=HIDDEN;Database=HIDDENXX;Trusted_Connection=yes;UID=HIDDENU;PWD=HIDDENP;"
cnt.Open
'String for SQL cmd
Dim p1 As Range
Set p1 = ActiveSheet.Cells(1, 4)
strSQL = "SELECT DBNAME.vItem.Upc FROM DBNAME.vItem WHERE vItem.ItemDesc=" & p1.Value
rst.ActiveConnection = cnt
rst.Open strSQL
ActiveSheet.Cells(1, 1).CopyFromRecordset rst
End Sub
Your code is subject to SQL injection. You could enclose the string literal in single quotes as shown in this answer to fix the syntax error, but that wouldn't fix the serious security issue.
Obligatory XKCD
So how do you securely parameterize a query? With parameterized queries!
Dim conn As ADODB.Connection
Set conn = New ADOBD.Connection
.ConnectionString = "connection string ideally using Windows Authentication"
.Open
Ideally your connection string doesn't contain any username or password; your server needs to be configured to support Windows Authentication for this to work - the query then executes with the credentials of the logged-in Windows user, with the privileges of that user.
Dim cmd As ADODB.Command
Set cmd.ActiveConnection = conn
cmd.CommandType = adCmdText
cmd.CommandText = "SELECT DBNAME.vItem.Upc FROM DBNAME.vItem WHERE vItem.ItemDesc = ?;"
Set up a Command object. The CommandText will be your SQL statement, but instead of concatenating the parameters into it, you use a ? question mark for each.
Dim itemDesc As ADODB.Parameter
Set itemDesc = New ADODB.Parameter
itemDesc.Type = adVarChar
itemDesc.Direction = adParamInput
itemDesc.Value = p1.Value
cmd.Parameters.Append(itemDesc)
Create a Parameter for each ? question mark in the SQL statement. You must supply a parameter for each ? question mark.
Dim results As ADODB.Recordset
Set results = cmd.Execute
You obtain the Recordset by calling the command's Execute method; the server deals with the parameters.
ActiveSheet.Cells(1, 1).CopyFromRecordset results
If all went well, the Recordset contains your results.
Always use parameterized queries: user input concatenated into SQL statements is a plague.
SQL needs to understand string literals as such; you need to delimit string literals with single quotes for the syntax to be valid.
Can you try this to see if that works?
strSQL = "SELECT DBNAME.vItem.Upc FROM DBNAME.vItem WHERE vItem.ItemDesc= '" & p1.Value & "'"

Error while storing records from Access field in array

Situation :
I have this code which stores all the records from the field Shipment ID in an array called arrayShipmentID.
Dim conn As New ADODB.Connection
Dim connStr As String
Dim rs As ADODB.Recordset
Dim ShipmentIDSQL As String
Dim arrayShipmentID() As Variant
connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & "P:\PathToTheAccessDatabase\" & "NewVersion.accdb" & ";"
conn.ConnectionString = connStr
conn.Open
' Store Shipment IDs
Set rs = New ADODB.Recordset
ShipmentIDSQL = "SELECT [Shipment ID] FROM 12Dec"
rs.Open ShipmentIDSQL, conn, adOpenStatic, adLockReadOnly, adCmdText
If Not rs.EOF Then
arrayShipmentID = rs.GetRows
End If
Dim i As Integer
For i = 0 To UBound(arrayShipmentID, 2)
Debug.Print arrayShipmentID(0, i)
Next i
Set rs = Nothing
In order to make sure it works I Debug.Print each element of the array.
Issue :
This code WORKS most of the time, but for some reason, sometimes I get as a value 'subscript out of range' (instead of 181 in my case) for MsgBox UBound(arrayShipmentID, 2) and of course in that case Debug.Print doesn't display anything in the Immediate Window.
Any ideas where could this come from ?
With DAO recordsets you often have to find the recordcount to retrieve all records. That might be the case for ADO as well:
RecordCount = ' Obtain true count of records.
arrayShipmentID = rs.GetRows(RecordCount)
Also, I normally declare the variable as a simple Variant:
Dim arrayShipmentID As Variant

Use SQL Statement in access 2007 [duplicate]

What's wrong with this code:
Visual Basic 6.0 With access 2007
Private Sub Command1_Click()
Dim Sell_tbl, Stock_Bottle, res As String
Sell_tbl = "SELECT Sum((Quantity)*12) FROM Sell_Detail Where Cateogry='Large'"
Stock_Bottle = "Select Sum(No_Of_Bottle) FROM Add_Bottle Where Cateogry='Large'"
res = ((Sell_tbl) - (Stock_Bottle))
Adodc1.RecordSource = Sell_tbl
Adodc1.Refresh
Adodc1.Caption = Adodc1.RecordSource
End Sub
Type Mismatch Error
I try to convert its result in other data type but it doesn't work. Can anyone help me?
Neither of these is a recordset, each is a string:
Sell_tbl = "SELECT Sum((Quantity)*12) FROM Sell_Detail Where Cateogry='Large'"
Stock_Bottle = "Select Sum(No_Of_Bottle) FROM Add_Bottle Where Cateogry='Large'"
You need something on the lines of:
Dim Sell_tbl As DAO.Recordset
Dim Stock_Bottle As DAO.Recordset
Set Sell_tbl = CurrentDB.Openrecordset _
("SELECT Sum((Quantity)*12) As Qty FROM Sell_Detail Where Cateogry='Large'")
Set Stock_Bottle = CurrentDB.Openrecordset _
("Select Sum(No_Of_Bottle) As Btl FROM Add_Bottle Where Cateogry='Large'")
res = Sell_tbl!Qty - Stock_Bottle!Btl
The above is a rough outline, it could do with tidying up.
The reason for the error is because of statement:
s = ((Sell_tbl) - (Stock_Bottle))
If you look above that line, you are setting two string variables to SQL -- which is text not numeric.
You need to open recordsets with those sql strings, then get the results, then perform the math.
It is what I want....
Private Sub Command2_Click()
Dim con As New ADODB.Connection
con.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" _
& App.Path & "\add_entry.mdb;Persist Security Info=False"
Dim rs As New ADODB.Recordset
Dim rs1 As New ADODB.Recordset
Dim result_hold As Integer
Dim large_tbl As String
Dim sell_large As String
large_tbl = "SELECT Sum(No_Of_Bottle) FROM add_cotton where Cateogry='Large'"
sell_large = "SELECT Sum(Quantity) FROM Sell_Detail where Cateogry='Large'"
rs.Open large_tbl, con, adOpenDynamic, adLockOptimistic
rs1.Open sell_large, con, adOpenDynamic, adLockOptimistic
result_hold = CInt(rs.Fields(0).Value) - CInt(rs1.Fields(0).Value)
Text1.Text = CStr(result_hold)
End Sub
'if u need to retreive whole colum use loop or etc.. but one thing is remember to you two sources
'never attach with single grid...