Store Query Results and Send Via Email VB6 - vb6

I want to send via email the results of a query which has multiple rows. At this moment, the lines of code I have only return the first row of the query result.
Dim Campo As String, AltNova As String, Message As String
Query = "SELECT * FROM MyTable"
rsSQL.Open Query, DSN, adOpenStatic
Do While Not rsSQL.EOF
Field1 = rsSQL("Field1").Value
Field2 = rsSQL("Field2").Value
rsSQL.MoveNext
Loop
rsSQL.Close
Set rsSQL = Nothing
Message = Field1 & Field2
I know it doesn't work like this, but I would really appreciate your help.

Related

How to write a gorm function for where clause with dynamic variables

I need to create a sql query :
SELECT * FROM users WHERE id = 10 AND name = "Chetan"
Now, gorm's where function looks like below,
// Where return a new relation, filter records with given conditions, accepts `map`, `struct` or `string` as conditions, refer http://jinzhu.github.io/gorm/crud.html#query
func (s *DB) Where(query interface{}, args ...interface{}) *DB {
return s.clone().search.Where(query, args...).db
}
Which mean it accepts a query and args. Example :
dbDriver.Where("id = ?", id).First(t)
How do i dynamically pass multiple variables. Example:
SELECT * FROM users WHERE id = 10 AND name = "Chetan"
SELECT * FROM users WHERE id = 10
SELECT * FROM users WHERE gender = "male" AND name = "Chetan" AND age = "30"
Is it poosible to write a single gorm function for such dynamic SQL statements?
You can use map[string]interface{} for coditions in .Where()
m := make(map[string]interface{})
m["id"] = 10
m["name"] = "chetan"
db.Where(m).Find(&users)
Just add your conditions in map then send inside where.
Or you can use struct in .Where(). Create a variable of struct and set those field for which you want to query and send inside where
db.Where(&User{Name: "chetan", Gender: "Male"}).First(&user)
NOTE: When query with struct, GORM will only query with those fields has non-zero value, that means if your field’s value is 0, '', false or other zero values, it won’t be used to build query conditions.
Referrence: https://gorm.io/docs/query.html#Struct-amp-Map
The first param of .Where() accepts string and the rest is variadic, this means you have the capability to modify the query and the values.
In the below example, I've prepared field1 & field2, and also value1 & value2 for representing the names of the fields I want to filter and their values respectively.
The values can be in any type since it's interface{}.
var field1 string = "id"
var value1 interface{} = 10
var field2 string = "age"
var value2 interface{} = "30"
dbDriver.Where(field1 " = ? AND " + field2 + " = ?", value1, value2).First(t)
Update 1
What if i am not sure what are number of parameter i will be passing? In this case we are hardcoding to two. What if that function/method passes 3 ?
One possible solution to achieve that, is by using slices to hold the criteria. You will have the control to dynamically adjust the fields and values.
fields := []string{"id = ?", "age = ?"}
values := []interface{}{10, "30"}
dbDriver.Where(strings.Join(fields, " AND "), values...).First(t)
Update 2
As per #Eklavya's comment, it's also possible to use a predefined struct object or a map instead of a string on the where clause.
db.Where(&User{Name: "jinzhu", Age: 20}).First(&user)
// SELECT * FROM users WHERE name = "jinzhu" AND age = 20 ORDER BY id LIMIT 1;
db.Where(map[string]interface{}{"name": "jinzhu", "age": 20}).Find(&users)
// SELECT * FROM users WHERE name = "jinzhu" AND age = 20;
Reference: GORM query reference

How to get the data in query(search result of hql)?

I am a novice to use jdbc and I have some problems.
I use hql to search data in MySQL, and the result is Query type. I don't know how to get the data from the "Query".This is my code:
final String hql = "select app.appkey,app.type from " + getClassName() +
"app where app.appkey<>'no-appkey' group by app.type";
Query query = getEntityManager().createQuery(hql);
Thanks a lot.
You have to do the following:
final String hql = "select app.appkey,app.type from " + getClassName() + " app where app.appkey<>'no-appkey' group by app.type";
Query query = getEntityManager().createQuery(hql);
query.list(); //or query.getSingleResult();
query.list() will give a list of results.
query.getSingleResult() will give you a object.
You can check this.
If you are expecting a list of results, so:
List<Object[]> results = query.getResultList();
If you are expect one single result:
Object[] result = query.getSingleResult(); // if more than one result was found, this method will throw a NonUniqueResultException
If column information will be stored in a position of the Object array. Example:
String appKey = (String) result[0];
String appType = (String) result[1];
But work with Object array is not good. Try to use Dto, like explained here.

CodeIgniter Active Record Where Not In String

I'm having an issue with CI Active Record's "Where Not In". I am trying to exclude a series of ID's. I couldn't understand why everything worked fine and dandy with one record, but not with multiple.
My Query
$this->db->where_not_in('crm.user_id', $ignore);
The problem is when I profile the the Query is wrong.
With a string of ID's
// $ignore = "12,13";
SELECT *
FROM (`crm`)
WHERE `crm`.`user_id` NOT IN ('16,13')
AND `survey` = 1
With a string of Quotes ID's
// $ignore = "'12','13'";
SELECT *
FROM (`crm`)
WHERE `crm`.`user_id` NOT IN ('\'16\',\'13\'')
AND `survey` = 1
Am I forced to do a loop of "or_where_not_in" or something like that?
where_in and where_not_in expect you to pass an array, not a string as the 2nd parameter.
$ignore = array(12, 13);
$this->db->where_not_in('crm.user_id', $ignore);
Link to the docs: http://www.codeigniter.com/userguide2/database/active_record.html

LINQ Lamba Select all from table where field contains all elements in list

I need a Linq statement that will select all from a table where a field contains all elements in a list<String> while searching other fields for the entire string regardless of words.
It's basically just a inclusive word search on a field where all words need to be in the record and string search on other fields.
Ie I have a lookup screen that allows the user to search AccountID or Detail for the entire search string, or search clientID for words inclusive words, I'll expand this to the detail field if I can figure out the ClientId component.
The complexity is that the AccountId and Detail are being searched as well which Basically stops me from doing the foreach in the second example due to the "ors".
Example 1, this gives me an the following error when I do query.Count() afterwards:
query.Count(); 'query.Count()' threw an exception of type 'System.NotSupportedException' int {System.NotSupportedException}
+base {"Local sequence cannot be used in LINQ to SQL implementations of query operators except the Contains operator."} System.SystemException {System.NotSupportedException}
var StrList = searchStr.Split(' ').ToList();
query = query.Where(p => p.AccountID.Contains(searchStr) || StrList.All(x => p.clientID.Contains(x)) || p.Detail.Contains(searchStr));
Example 2, this gives me an any search word type result:
var StrList = searchStr.Split(' ').ToList();
foreach (var item in StrList)
query = query.Where(p => p.AccountID.Contains(searchStr) || p.clientID.Contains(item) || p.Detail.Contains(searchStr));
Update
I have a table with 3 fields, AccountID, ClientId, Details
Records
Id, AccountID, CLientId, Details
1, "123223", "bobo and co", "this client suxs"
2, "654355", "Jesses hair", "we like this client and stuff"
3, "456455", "Microsoft", "We love Mircosoft"
Search examples
searchStr = "232"
Returns Record 1;
searchStr = "bobo hair"
Returns no records
searchStr = "bobo and"
Returns Record 1
searchStr = "123 bobo and"
Returns returns nothing
The idea here is:
if the client enters a partial AccountId it returns stuff,
if the client wants to search for a ClientId they can type and cancel down clients by search terms, ie word list. due to the large number of clients the ClientID Will need to contain all words (in any order)
I know this seems strange but it's just a simple interface to find accounts in a powerful way.
I think there are 2 solutions to your problem.
One is to count the results in memory like this:
int count = query.ToList().Count();
The other one is to not use All in your query:
var query2 = query;
foreach (var item in StrList)
{
query2 = query2.Where(p => p.clientID.Contains(item));
}
var result = query2.Union(query.Where(p => p.AccountID.Contains(searchStr) || p.Detail.Contains(searchStr)));
The Union at the end acts like an OR between the 2 queries.

Linq Compiled Queries and int[] as parameter

I'm using the following LINQ to SQL compiled query.
private static Func<MyDataContext, int[], int> MainSearchQuery =
CompiledQuery.Compile((MyDataContext db, int[] online ) =>
(from u in db.Users where online.Contains(u.username)
select u));
I know it is not possible to use sequence input paramter for a compiled query and im getting “Parameters cannot be sequences” error when running it.
On another post here related , I saw that there is some solution but I couldn't understand it.
Does anyone know to use complied query with array as input paramter?
Please post example if you do.
Like the post that you referenced, it's not really possible out of the box. The post also references creating your own query provider, but it's a bit of overhead and complexity that you probably don't need.
You have a few options here:
Don't use a compiled query. Rather, have a method which will create a where clause from each item in the array resulting in something like this (psuedo-code):
where
online[0] == u.username ||
online[1] == u.username ||
...
online[n] == u.username
Note that you would have to use expression here to create each OR clause.
If you are using SQL Server 2008, create a scalar valued function which will take a table-valued parameter and a value to compare againt. It will return a bit (to indicate if the item is in the values in the table). Then expose that function through LINQ-to-SQL on your data context. From there, you should be able to create a CompiledQuery for that. Note that in this case, you should take an IEnumerable<string> (assuming username is of type string) instead of an array, just because you might have more than one way of representing a sequence of strings, and to SQL server for this operation, it won't matter what the order is.
One solution that I have found myself doing (for MS SQL 2005/2008). And I'm not sure if it is appropriate in all scenarios is to just write dynamic sql and execute it against the datacontext using the ExecuteQuery method.
For example, if I have an unbounded list that I am trying to pass to a query to do a contains...
' Mock a list of values
Dim ids as New List(of Integer)
ids.Add(1)
ids.Add(2)
' ....
ids.Add(1234)
Dim indivs = (From c In context.Individuals _
Where ids.Contains(c.Id) _
Select c).ToList
I would modify this query to create a SQL string to execute against the database directly like so...
Dim str As New Text.StringBuilder("")
Dim declareStmt as string = "declare #ids table (indivId int) " & vbcrlf)
For i As Integer = 0 To ids.Count - 1
str.Append("select " & ids(i).ToString() & " & vbcrlf)
If i < ids.Count Then
str.Append("union " & vbcrlf)
End If
Next
Dim selStatement As String = "select * From " & context.Mapping.GetTable(GetType(Individuals)).TableName & _
" indiv " & vbcrlf & _
" inner join #ids ids on indiv.id = ids.id"
Dim query = declareStmt & str.ToString & selStatement
Dim result = context.ExecuteQuery(of Individual)(query).ToList
So barring any syntax errors or bugs that I coded (the above is more or less psuedo code and not tested), the above will generate a table variable in SQL and execute an inner join against the desired table (Individuals in this example) and avoid the use of a "IN" statement.
Hope that helps someone out!

Resources