I am using this code to retrieve no of machines (count)...
Dim strCntSr As String = "SELECT count(sr_no) FROM Vendor_Machine WHERE chaln_no='" & cmbChal_no.Text & "'"
comm_getCnt = New OleDb.OleDbCommand(strCntSr, cnnOLEDB)
comm_getCnt.ExecuteNonQuery()
***Here I want to set result of the above query [count(sr_no)] as text of lblMachine***
lblMachine.Text =
Please suggest me the code.. Thank you..
ExecuteNonQuery return only the number of the rows affected not the value/s returned by the query.
In your case the correct method to use is ExecuteScalar that returns the first column of the first row obtained by the query.
Notice also that is a very bad practice to build query text using string concatenation.
The problems are Sql Injection and correct parsing of text provided by you.
Dim strCntSr As String = "SELECT count(sr_no) FROM Vendor_Machine WHERE chaln_no=?"
comm_getCnt = New OleDb.OleDbCommand(strCntSr, cnnOLEDB)
comm_getCnt.Parameters.AddWithValue("#p1", cmbChal_no.Text)
Dim result = comm_getCnt.ExecuteScalar()
lblMachine.Text = Convert.ToInt32(result);
Related
I am writing some script to read the sql query result at Intouch environment, it's not exactly C# language but similar. I just want to get the "1" stored in my "SQLTest" variable (Define as a string data type).
Here's the result of my sql query
And here is my code:
Dim objDB As System.Data.SqlClient.SqlConnection;
Dim objCmd As System.Data.SqlClient.SqlCommand;
Dim objDR As System.Data.SqlClient.SqlDataReader;
Dim objTbl As System.Data.DataTable;
Dim sDBConnStr As String;
Dim sSQL As String;
Dim bOk As Boolean;
sDBConnStr = "Server=Desktop-3J641FK;Database=Runtime;Integrated Security=True;";
'' Connect and open the database
objDB = New System.Data.SqlClient.SqlConnection(sDBConnStr);
objDB.Open();
sSQL = "SELECT sum (case when EventLogKey = '5' and DetectDateTime between '2022-07-21 11:00:20' and '2022-07-25 11:00:20' then 1 else 0 end) FROM [Runtime].[dbo].[EventHistory]";
'' Invoke the SQL command
objCmd = New System.Data.SqlClient.SqlCommand(sSQL, objDB);
'' Retrieve the queried fields from the query into the reader
objDR = objCmd.ExecuteReader();
InTouch:SQLTesting = objDR.Read();
while objDR.Read() == true
InTouch:SQLTest = objDR.GetValue(0).ToString;
endwhile;
objDR.Close();
objDB.Dispose();
objCmd.Dispose();
InTouch:SQLTesting = objDR.Read();
while objDR.Read() == true
You are calling Read twice, so what do you expect to happen?
If there will be exactly one row, just call Read.
If there will be zero or one row, call Read with an if statement.
If there may be more than one row, call Read with a while loop.
Do one and only one of the above. If there might be more than one row and you want to do something different if there are no rows, use the HasRows property first, then use the while loop.
Having said all that, if there will only be one value in the result set then you should be calling ExecuteScalar, so the data reader is irrelevant:
InTouch:SQLTest = objCmd.ExecuteScalar().ToString();
I think your While loop is unnecessary here as you Read the sqldata reader already before While and you are using Sum in your sql which will return one value always. Try this :
InTouch:SQLTesting = objDR.Read();
InTouch:SQLTest = objDR.GetValue(0).ToString;
Objective: I'm building VBA code to filter through an address table SunstarAccountsInWebir_SarahTest. I want to loop through first and see if the address is "valid".
If it is not valid – export to different table.
If it is valid – it enters another nested if/then within "valid" address rows:
If their ID, external_nmad_id matches the ID of the second table 1042s_FinalOutput_7, I want to update one of the columns in the second table box13c_Address.
If it doesn't match an ID of the second table – it will be exported to a different table.
My problem is when I run my code it is returning
Run-Time error 3078: cannot find table or query
(it's breaking at the line where I compare the value of the cell (as string) against the DCount of table 2). If I remove the quotes around it I get a different error:
Type mismatch against the DCount
I feel like I'm missing something simple but can't tell what. How can I get my code to match a string value called in !external_nmad_id against the rest of the table called in my string? DCount("[ID]", StrSQL1)
Public Sub EditFinalOutput2()
'set variables
Dim i As Long
Dim qs As DAO.Recordset
Dim ss As DAO.Recordset
Dim StrSQL1 As DAO.Recordset
Dim IRSfileFormatKey As String
Dim external_nmad_id As String
Dim nmad_address_1 As String
Dim nmad_address_2 As String
Dim nmad_address_3 As String
Dim mytestwrite As String
'open reference set
Set db = CurrentDb
Set qs = db.OpenRecordset("SunstarAccountsInWebir_SarahTest")
'Set ss = db.OpenRecordset("1042s_FinalOutput_7")
'Set StrSQL1 = db.OpenRecordset("SELECT RIGHT(IRSfileFormatKey, 10) As ID
'FROM 1042s_FinalOutput_7;")
With qs.Fields
intCount = qs.RecordCount - 1
For i = 0 To intCount
If (IsNull(!nmad_address_1) Or (!nmad_address_1 = !nmad_city) Or (!nmad_address_1 = !Webir_Country) And IsNull(!nmad_address_2) Or (!nmad_address_2 = !nmad_city) Or (!nmad_address_2 = !Webir_Country) And IsNull(!nmad_address_3) Or (!nmad_address_3 = !nmad_city) Or (!nmad_address_3 = !Webir_Country)) Then
DoCmd.RunSQL "INSERT INTO Addresses_ToBeReviewed SELECT SunstarAccountsInWebir_SarahTest.* FROM SunstarAccountsInWebir_SarahTest WHERE (((SunstarAccountsInWebir_SarahTest.external_nmad_id)='" & qs!external_nmad_id & "'));"
Else:
Set ss = db.OpenRecordset("1042s_FinalOutput_7")
Set StrSQL1 = db.OpenRecordset("SELECT RIGHT(IRSfileFormatKey, 10) As ID FROM 1042s_FinalOutput_7;")
If !external_nmad_id = DCount("[ID]", StrSQL1) Then
ss.Edit
ss.Fields("box13c_Address") = qs.Fields("nmad_address_1") & qs.Fields("nmad_address_2") & qs.Fields("nmad_address_3")
ss.Update
Else: DoCmd.SetWarnings False
DoCmd.RunSQL "INSERT INTO Addresses_NotUsed SELECT SunstarAccountsInWebir_SarahTest.* FROM SunstarAccountsInWebir_SarahTest WHERE (((SunstarAccountsInWebir_SarahTest.external_nmad_id)='" & qs!external_nmad_id & "'));"
DoCmd.SetWarnings True
End If
End If
qs.MoveNext
Next i
End With
'close reference set
qs.Close
Set qs = Nothing
ss.Close
Set ss = Nothing
End Sub
The issue is that the DCount function cannot operate directly against a Recordset.
You are declaring StrSQL1 as a RecordSet object and setting it to a RecordSet based on your Select statement.
Set StrSQL1 = db.OpenRecordset("SELECT RIGHT(IRSfileFormatKey, 10) As ID FROM 1042s_FinalOutput_7;")
You are then trying to pass this RecordSet to the DCount function which cannot accept a RecordSet object as the Domain parameter. As you can see in MSDN the DCount function requires a String parameter in the second position to define the "query" that you wish to "Count". Hence the 3078 error. When you remove the quotes around [ID] in your DCount line, you get Type Mismatch as a compile error because [ID] is not a String or String variable.
After you resolve that, you might want to reconsider your If statement. You haven't provided a sample of what kind of value !external_nmad_id will contain, other than the fact that it is a String value. The DCount function is going to return the number of rows found in the Domain (query) that you told it to count, so it appears you will be comparing a string (which may possibly contain alpha characters) to a number. Access will implicitly convert the DCount numeric result to a String for the sake of the comparison, but if your !external_nmad_id String is truly 10 characters or contains alpha characters, they will never match.
You cannot use a VBA recordset inside a domain aggregate like DCount as a string literal is required for table/query name argument. Simply save your query and then reference it by name in DCount.
SQL (save as query)
SELECT RIGHT(IRSfileFormatKey, 10) As ID FROM 1042s_FinalOutput_7;
VBA
If !external_nmad_id = DCount("[ID]", "mySavedQuery") Then
...
End If
I need to send data in string format to mysql. By default vb.net interprets 0.5 as 0,5 which MySql won't accept. I know I could write floatval.tostring.replace(",", ".") to make it fit but I was wondering if it was possible to make it more comfortable so that an implicit conversion from float to string would produce a dot instead of a comma?
EDIT: per request, current code
Public Sub InsertInto(Values As IEnumerable(Of String))
Dim ValStr As String = ""
For Each V In Values
ValStr &= "'" & V & "',"
Next
Dim Command = New MySqlCommand("INSERT INTO " & Table & " VALUES (" & ValStr.Substring(0, ValStr.Length - 1) & ");", Connection)
Command.ExecuteNonQuery()
End Sub
this method is a part of a mysql connection wrapper and the properties "Connection" and "Table" are preassigned.
My test code calls the function as follows:
dimdum.InsertInto({"DEFAULT", (0.5).ToString.Replace(",", "."), "here is text"})
the test table columns are auto iterating int as primary key, a float and a varchar
As I have saind in my comment above, I am afraid that you need to revise a lot of your code. As is you have a lot of problems, the worst is the Sql Injection that sooner or later you have to fix, but your try to convert everything in a string has also the drawback that the conversion of decimals, dates and other floating points values give more immediate troubles than the Sql Injection one.
There is only one way to get out and it is the use of parameterized queries. More code to write but after a while it is very straightforward.
So for example you should rewrite your code to something like this
Public Sub InsertInto(sqlText As String, Values As List(Of MySqlParameter))
Using Connection = New MySqlConnection(... connectionstring here (or a global variable ....)
Using Command = New MySqlCommand(sqlText, Connection)
Connection.Open()
If Values IsNot Nothing Then
Command.Parameters.AddRange(values.ToArray)
End If
Command.ExecuteNonQuery()
End Using
End Using
End Sub
and call it with this
Dim decValue As Decimal = 0.5
Dim strValue As String = "Test"
Dim dateValue As DateTime = DateTime.Today
Dim parameters = New List(Of MySqlParameter)()
parameters.Add(New MySqlParameter() With { .ParameterName = "#p1",
.DbType = MySqlDbType.Decimal,
.Value = decValue})
parameters.Add(New MySqlParameter() With {.ParameterName = "#p2",
.DbType = MySqlDbType.String,
.Value = strValue})
parameters.Add(New MySqlParameter() With {.ParameterName = "#p3",
.DbType = MySqlDbType.Date,
.Value = dateValue})
InsertInto("INSERT INTO youTable VALUES(#p1, #p2, #p3)", parameters)
Note that now InserInto is just a simple routine that receives the command text and the parameters expected by the text, add them to the command, opens the connection, executes everything and exits closing the connection.
Note also that, with a parameterized queries, your sql command is totally void of the mess caused by single quotes for strings, formatting rules for dates and the handling of the decimal point is nowhere in sight
(A side note. This INSERT INTO text suppose that your table has exactly three fields and you supply the values for all of them, if you want to insert only a subset of fields then you need to pass them to the method as a third parameter )
Specify CultureInfo:
Dim n As Single
Dim s As String
n = Math.PI
s = n.ToString("F2", New System.Globalization.CultureInfo("en-US"))
s will be "3.14", even if your computer is set for a different format.
I have the following code in my code behind:
Dim name As String
name.text= Staff.LoadName(StaffID)
The following query in my Class:
Public Function LoadName(ByVal ID As String)
Dim ds As New DataSet
Dim SQL As String = ""
SQL="select name from Staff where StaffID='" & ID & "' "
ds = Common.QueryDataByDataset(SQL)
ds.Tostring()
Return ds
End Function
But the name.Text doesn't show the value. How to I get the single value and convert it to string to display? Thanks
I am guessing the Common.QueryDataByDataset is from your library or some third party. Assuming it is executing the query and populating the dataset, you should be able to change the last two lines of the LoadName function to this:
String name = ds.Tables.Item("Staff").Rows(0)("name").ToString()
return name
You should add error handling in this method. For example, check to make sure the query returns exactly one result. Also, this method appears to be susceptible to SQL injection: http://en.wikipedia.org/wiki/SQL_injection
I have a query saved in the queries section. I am running the query from VBA. Is it possible to save the results of this query to a string?
An ADO Recordset has a GetString method which might be useful to you.
I have a query named qryListTables which looks like this:
SELECT m.Name AS tbl_name
FROM MSysObjects AS m
WHERE
(((m.Name) Not Like "msys%"
And (m.Name) Not Like "~%")
AND ((m.Type)=1))
ORDER BY m.Name;
Notice that query uses % instead of * as the wildcard character. The reason for that choice is that ADO requires ANSI wild card characters (% and _ instead of * and ?).
I can use the following function to spit out a string containing the quoted names of regular tables in my database, separated by semicolons, by calling it like this:
? DemoGetString("qryListTables", True)
Public Function DemoGetString(ByVal pQueryName As String, _
Optional ByVal AddQuotes As Boolean = False) As Variant
'* early binding requires a reference to Microsoft ActiveX
'* Data Objects Library
'Dim rs As ADODB.Recordset
'Set rs = New ADODB.Recordset
'* use late binding; no referenced needed
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
Dim varOut As Variant
rs.Open pQueryName, CurrentProject.Connection
If AddQuotes Then
varOut = """" & rs.GetString(2, , , """;""") '2 = adClipString
' strip off last quote
If Len(varOut & vbNullString) > 0 Then
varOut = Left(varOut, Len(varOut) - 1)
End If
Else
varOut = rs.GetString(2, , , ";") '2 = adClipString
End If
rs.Close
Set rs = Nothing
DemoGetString = varOut
End Function
Ok.. taking a complete shot in the dark here...
The query you are running is literally a query... think of it as its OWN table... it can be referenced as you would any other table, and can be queried against.
If you are trying to return a single string item based on a single criteria your best bet is a Dlookup:
Lookup = Nz(DLookup(string Field, string Table, string Criteria), "")
If your looking for a group of records:
dim tsSQL as string
stSQL = "SELECT * FROM table WHERE field=criteria"
dim toRecordset as new ADODB.Recordset
toRecordset.open stSQL, CurrentProject.AccessConnection, int Keyset, int Lock
Then you can directly access the fields by:
If toRecordset.RecordCount > 0 then
String = toRecordset!FieldName
End If
W/o more information... that about it...
Also it works in the other direction as well..
You can do:
toRecordset.AddNew
toRecordset!Field = Value
toRecordset.Update
I hope somewhere in there is an answer for you.
To get the entire query you could change up the select statement from example one to "SELECT * FROM query name" and that should pull the whole thing in.