Been away form coding and don't have my reference docs. Have this bit of code.
Private Sub RunPivotButton_Click()
Dim TblLenSQL As String
TblLenSQL = "SELECT Count(dbo_Transaction_Table.Sequence_Number) AS
CountOfSequence_Number," _
TblLenSQL = TblLenSQL & " From dbo_Transaction_Table"
Dim CRDcon As ADODB.Connection
Set TranCnt = CurrentProject.Connection
Dim CountRS As New ADODB.Recordset
crdRs.ActiveConnection = TranCnt
crdRs.CursorType = adOpenStatic
crdRs.Open TblLenSQL
End Sub
When I add the second line of code for building the query I get
"Expected Ed of statement TblLenSQL = TblLenSQL & " From
dbo_Transaction_Table"
Something basic and trivial but I can't see it.
Thanks
jpl458
Either concatenate in a single statement - using the line-continuation character _ ...
TblLenSQL = "SELECT Count(dbo_Transaction_Table.Sequence_Number) AS CountOfSequence_Number," & _
" From dbo_Transaction_Table"
... or don't - using multiple statements ...
TblLenSQL = "SELECT Count(dbo_Transaction_Table.Sequence_Number) AS CountOfSequence_Number,"
TblLenSQL = TblLenSQL & " From dbo_Transaction_Table"
... there is no both.
Your SQL statement is incomplete (SELECT x, FROM y) but you are probably aware of that.
Related
SQL = "UPDATE `tblitems` SET `itemsOnHand` = `itemsOnHand` - '" & PartnumItemsNumericUpDown.Value & "' WHERE `itemID` = '" & itemIDTextBoxX.Text & "' ;"
SQL = "UPDATE `tblitems` SET `itemsOnHand` = `itemsOnHand` + '" & PartnumItemsNumericUpDown.Value & "' WHERE `itemID` = '" & itemIDTextBoxX.Text & "' ;"
--- Just want to ask why the first sub function sql command (-) works but (+) wont...please help. itemsOnHand is integer type.
Please DO NOT concatenate strings to build sql command text. ALWAYS use Parameters it avoid sql injection. Parameter values are not executable code but a simple concatenation can hold "Delete * From tblitems."
I had to guess at the datatypes for the parameters.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim ItemId As Integer
If Not Integer.TryParse(itemIDTextBoxX.Text, ItemId) Then
MessageBox.Show("Please enter a number in Item Id.")
Return
End If
Dim Sql = "UPDATE `tblitems` SET `itemsOnHand` = `itemsOnHand` - #PartNumber WHERE `itemID` = #ItemID"
Using con As New MySqlConnection(ConStr),
cmd As New MySqlCommand(Sql, con)
cmd.Parameters.Add("#PartNumber", MySqlDbType.Int32).Value = PartnumItemsNumericUpDown.Value
cmd.Parameters.Add("#ItemID", MySqlDbType.Int32).Value = ItemID
con.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
You are much less likely to run into problems with + and - using parameters since you don't need all the single quotes and double quotes.
The minus sign was interpreted as an arithmetic operator and the plus sign was interpreted as a concatenation character.
Please find the below table and code. I am facing Invalid use of Null Error
Table 1
Table 2
VBA code:-
Sub sql()
sql_string = "Select [Sheet1$].[Sr], [Sheet2$].[Name], [Sheet2$].[Value] From [Sheet1$]" & _
" Inner Join [Sheet2$] On CInt([Sheet1$].[Sr]) = CInt(Mid([Sheet2$].[Name],InStr(1,[Sheet2$].[Name],""#"")+1))"
sq = SQL_query(sql_string)
end sub
Function SQL_query(ByRef sql_string As Variant)
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
strFile = ThisWorkbook.FullName
strCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
strSQL = sql_string
rs.Open strSQL, cn
Sheet5.Range("A21").CopyFromRecordset rs ''HERE I AM FACING ERROR
End Function
Please guide me.. on my below error.
In table2 column Sr after # there are some number's which is similar to table1 column Sr number's.I want to do inner join as per that particular number.
required output.
Start by writing Option Explicit on top of the module. Why does my code run without 'Option Explicit' but fail with it?
Then change the Sub sql() to something like this:
Function sql_string() as string
sql_string = "Select [Sheet1$].[Sr], [Sheet2$].[Name], [Sheet2$].[Value] From [Sheet1$]" & _
" Inner Join [Sheet2$] On CInt([Sheet1$].[Sr]) = CInt(Mid([Sheet2$].[Name],InStr(1,[Sheet2$].[Name],""#"")+1))"
end sub
In the immediate window, write ?sql_string and see what you get.
Find a way to test what you get
So here is my code below.
qry = "SELECT * FROM `tblsubjects` WHERE `GRADELEVEL` = " & lblgrade.Text & " AND `SUBJECTNAME` <> (SELECT `SUBJECTNAME` FROM `tblschedule` WHERE `SECTIONNAME` = '" & lblsect.Text & "')"
it came from may vb application. I think the error came from the query. t I'm making a scheduling system. On that query, i was trying to load the subjects that has not been scheduled on that gradelevel and section on to combo box. but that error comes out when i try to add more schedule on this section.
enter image description here
Here is my whole code on this function:
Private Sub subjectload()
con = New MySqlConnection
con.ConnectionString = "server=localhost;user id=root;password='';database=kccbeslis"
If DataGridView.Rows.Count > 0 Then
Try
con.Open()
qry = "SELECT * FROM `tblsubjects` WHERE `GRADELEVEL` = " & lblgrade.Text & " AND `SUBJECTNAME` <> (SELECT `SUBJECTNAME` FROM `tblschedule` WHERE `SECTIONNAME` = '" & lblsect.Text & "')"
cmd = New MySqlCommand(qry, con)
rdr = cmd.ExecuteReader
While rdr.Read
Dim subname = rdr.GetString("SUBJECTNAME")
cbsubject.Items.Add(subname)
End While
con.Close()
Catch ex As Exception
MessageBox.Show(ErrorToString)
End Try
Else
Try
con.Open()
qry = "SELECT * FROM `tblsubjects` WHERE `GRADELEVEL` = " & lblgrade.Text & ""
cmd = New MySqlCommand(qry, con)
rdr = cmd.ExecuteReader
While rdr.Read
Dim subname = rdr.GetString("SUBJECTNAME")
cbsubject.Items.Add(subname)
End While
con.Close()
Catch ex As Exception
MessageBox.Show(ErrorToString)
End Try
End If
End Sub
help me pls!
Subquery SELECTSUBJECTNAMEFROMtblscheduleWHERESECTIONNAME= '" & lblsect.Text & "' results more than 1 records. You are using <> instead of not in, use Not In clause and try.
It appears your sub select (SELECT subjectname FROM tblscheduler where..) has multiple schedules with the same 'sectionname' you are providing, therefore is returning more than 1 row.
Are you sure your sectionname column is unique per tblschedule entry? Try a count and group by to see if you have multiple records;
SELECT COUNT(*) FROM tblschedule GROUP BY sectionname;
You could try replacing <> with NOT IN if you require multiple rows.
Yes, that's cause your subquery returning more than 1 record and <> operator expects scalar value and list of values. You should rather use NOT IN operator like
AND `SUBJECTNAME` NOT IN (SELECT `SUBJECTNAME` FROM `tblschedule` WHERE `SECTIONNAME` = '" & lblsect.Text & "')
BTW, do you know your posted code is very much vulnerable to SQL Injection. You should consider using parameterized queries to avoid the same.
Use NOT IN instead of <>
qry = "SELECT * FROM tblsubjects WHERE GRADELEVEL = " & lblgrade.Text & " AND SUBJECTNAME NOT IN (SELECT SUBJECTNAME FROM tblschedule WHERE SECTIONNAME = '" & lblsect.Text & "')"
Error: "Run-time error '3061' Too few parameters. Expected 2.
I wrote this simple function that returns the remaining percentage calculated for number of records changed. It is supposed to occur when the user updates the field called 'percentage' I am certain the code below should work, but obviously something is wrong. It occurs on the line:
Set rs = db.OpenRecordset("SELECT Tier1, [Percentage], Tier3 AS Battalion, Month " _
& "FROM tbl_CustomPercent " _
& "WHERE (((Tier1)=[Forms]![frmEntry]![cmbImport_T1]) AND ((Month)=[Forms]![frmEntry]![cmbMonth]));", dbOpenSnapshot)
I wonder how it could fail when the very same query is what populates the 'record source' for the form with the 'percentage' textbox.
Function RemainingPercentAvailable() As String
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strSQL As String
Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT Tier1, [Percentage], Tier3 AS Battalion, Month " _
& "FROM tbl_CustomPercent " _
& "WHERE (((Tier1)=[Forms]![frmEntry]![cmbImport_T1]) AND ((Month)=[Forms]![frmEntry]![cmbMonth]));", dbOpenSnapshot)
Dim CurrentTotal As Single
CurrentTotal = 0
If Not (rs.EOF And rs.BOF) Then
rs.MoveFirst
Do Until rs.EOF = True
CurrentTotal = CurrentTotal + rs!Percentage
rs.MoveNext
Loop
End If
RemainingPercentAvailable = "Remaing available: " & Format(1 - CurrentTotal, "0.000%")
Set rs = Nothing
Set db = Nothing
End Function
Adapt your code to use the SELECT statement with a QueryDef, supply values for the parameters, and then open the recordset from the QueryDef.
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim rs As DAO.Recordset
Dim strSQL As String
strSQL = "SELECT Tier1, [Percentage], Tier3 AS Battalion, [Month] " _
& "FROM tbl_CustomPercent " _
& "WHERE (((Tier1)=[Forms]![frmEntry]![cmbImport_T1]) AND (([Month])=[Forms]![frmEntry]![cmbMonth]));"
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, strSQL )
' supply values for the 2 parameters ...
qdf.Parameters(0).Value = Eval(qdf.Parameters(0).Name)
qdf.Parameters(1).Value = Eval(qdf.Parameters(1).Name)
Set rs = qdf.OpenRecordset
Note: Month is a reserved word. Although that name apparently caused no problems before, I enclosed it in square brackets so the db engine can not confuse the field name with the Month function. It may be an unneeded precaution here, but it's difficult to predict exactly when reserved words will create problems. Actually, it's better to avoid them entirely if possible.
This one is calling a query directly in a DAO.Recordset and it works just fine.
Note the same 'Set rs = db.OpenRecordset(strSQL, dbOpenDynaset) This is a parameter SQL as well.
The only difference is with this one is that I DIDN'T need to move through and analyze the recordset - but the error occurs on the 'Set rs = " line, so I wasn't able to get further anyway.
Dim rs As DAO.Recordset
Dim db As DAO.Database
Dim strSQL As String
strSQL = "SELECT Sum(tbl_SP.AFP) AS AFP_TOTAL, tbl_SP.T1_UNIT " _
& "FROM tbl_SP " _
& "GROUP BY tbl_SP.T1_UNIT " _
& "HAVING (((tbl_SP.T1_UNIT)='" & strUnit & "'));"
Set db = CurrentDb
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset)
AFP_Total = rs!AFP_Total
There is an even simpler way to calculate the total percentage.
Instead of looping through the records, you can use the DSum() function.
Note that DSum will return Null if there are no records, so you need to wrap it in Nz().
Just for fun, here is your function but written as one single statement:
Function RemainingPercentAvailable() As String
RemainingPercentAvailable = "Remaining available: " & Format(1 - _
Nz(DSum("Percentage", _
"tbl_CustomPercent", _
"Tier1 = " & QString(cmbImport_T1) & _
" AND [Month] = " & QString(cmbMonth))) _
, "0.000%")
End Function
I don't recommend building a temporary parameterized query in VBA, because it makes the code too complicated. And slower. I prefer to build "pure" SQL that will run directly in the db engine without any callbacks to Access. I'm assuming that your function is defined in the frmEntry form, and that cmbImport_T1 and cmbMonth are string fields. If they are numeric, omit qString().
Here is my version of your function. It handles the empty-recordset case correctly.
Function RemainingPercentAvailable() As String
Dim CurrentTotal As Double, q As String
q = "SELECT Percentage" & _
" FROM tbl_CustomPercent" & _
" WHERE Tier1 = " & QString(cmbImport_T1) & _
" AND [Month] = " & QString(cmbMonth)
CurrentTotal = 0
With CurrentDb.OpenRecordset(q)
While Not .EOF
CurrentTotal = CurrentTotal + .Fields("Percentage")
.MoveNext
Wend
End With
RemainingPercentAvailable = "Remaining available: " & _
Format(1 - CurrentTotal, "0.000%")
End Function
' Return string S quoted, with quotes escaped, for building SQL.
Public Function QString(ByVal S As String) As String
QString = "'" & Replace(S, "'", "''") & "'"
End Function
Good evening,
I've been working at this all day today to no avail. I'm using the code below to take user input in a textbox and search through the database (as the user types) and present the results in a ListView control. It works as-is, but I know it's insecure because it's not parametized. I know how to add the parameter to the MySQLCommand object but can't figure out how to add it to the query. Any help would be greatly appreciated, thanks.
HERE'S MY CODE:
Private Sub TextBoxSearch_TextChanged(sender As Object, e As System.EventArgs) Handles TextBoxSearch.TextChanged
Dim dbConn As New MySqlConnection(String.Format("Server={0};Port={1};Uid={2};Password={3};Database=accounting", FormLogin.ComboBoxServerIP.SelectedItem, My.Settings.DB_Port, My.Settings.DB_UserID, My.Settings.DB_Password))
Dim dbQuery As String = ""
Dim dbCmd As New MySqlCommand
Dim dbReader As MySqlDataReader
Dim a, b, c, d, f, g
Try
dbQuery = "SELECT * FROM cc_master INNER JOIN customer ON customer.accountNumber = cc_master.customer_accountNumber " & _
"WHERE nameCOMPANY OR accountNumber LIKE '%" & TextBoxSearch.Text & "%' " & _
"ORDER BY nameCOMPANY ASC"
dbConn.Open()
dbCmd = New MySqlCommand(dbQuery, dbConn)
dbReader = dbCmd.ExecuteReader()
ListViewRecords.Items.Clear()
Do While dbReader.Read()
a = (dbReader.Item("ccID").ToString())
b = (dbReader.Item("accountNumber").ToString())
c = (dbReader.Item("nameCOMPANY").ToString())
d = DecryptCard(dbReader.Item("ccNumber").ToString())
f = (dbReader.Item("ccExpireMonth").ToString())
g = (dbReader.Item("ccExpireYear").ToString())
Dim item As ListViewItem = ListViewRecords.Items.Add(a)
item.SubItems.Add(b)
item.SubItems.Add(c)
item.SubItems.Add(d)
item.SubItems.Add(f)
item.SubItems.Add(g)
Loop
dbReader.Close()
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
End Try
dbConn.Close()
dbCmd.Dispose()
End Sub
I'm assuming your issue is the wildcards not working correctly. This does not work as the parameter cannot be enclosed in quotes.
dbQuery = "SELECT * FROM cc_master INNER JOIN customer ON customer.accountNumber = cc_master.customer_accountNumber " & _
"WHERE nameCOMPANY OR accountNumber LIKE '%?ParameterName%' " & _
"ORDER BY nameCOMPANY ASC"
To fix, you can concat the wildcards into your parameter first and then insert it into your query.
Dim parameter = "%" & TextBoxSearch.Text & "%"
dbQuery = "SELECT * FROM cc_master INNER JOIN customer ON customer.accountNumber = cc_master.customer_accountNumber " & _
"WHERE nameCOMPANY OR accountNumber LIKE ?ParameterName " & _
"ORDER BY nameCOMPANY ASC"
Did you mean something like:
dbQuery = "SELECT * FROM cc_master INNER JOIN customer " & _
"ON customer.accountNumber = cc_master.customer_accountNumber " & _
"WHERE nameCOMPANY OR accountNumber LIKE '%' + ? + '%' " & _
"ORDER BY nameCOMPANY ASC"
dbConn.Open()
dbCmd.Connection = dbConn
dbCmd.CommandType = CommandType.Text
dbCmd.CommandText = dbQuery
dbCmd.Parameters.AddWithValue("?", TextBoxSearch.Text)
dbReader = dbCmd.ExecuteReader()
However, I think you would probably be better with a stored procedure and pass parameters to that http://www.mysqltutorial.org/stored-procedures-parameters.aspx