querying sqlite database using "between" with cursor - android-studio

newbie here.. i have a two data sets which is "time-in", and "time-out" and i would like to query this two using "between" so that the data ive should get was the filtered on my "time-in" to my "time-out"...
this is my query data (get all data).
public Cursor retrieveHistoryLocationFromLocalDatabase(SQLiteDatabase db)
{
String[] columnNames =
{
HISTORY_SERIAL_NUMBER,
HISTORY_LATITUDE,
HISTORY_LONGITUDE,
HISTORY_DATE_TIME,
HISTORY_SPEED,
HISTORY_PORT
};
return (db.query(TABLE_HISTORY_FLEET_LOCATION, columnNames,null,
null,null, null, null));
}

Use rawQuery() method to prepare select statement.
public Cursor retrieveHistoryLocationFromLocalDatabase(SQLiteDatabase db, String timeIn, String {
String sql = "SELECT HISTORY_SERIAL_NUMBER, HISTORY_LATITUDE,"
+ " HISTORY_LONGITUDE, HISTORY_DATE_TIME, HISTORY_SPEED, HISTORY_PORT"
+ " FROM your_table_name"
+ " WHERE your_time_in_out_column BETWEEN '" + timeIn + "' AND '" + timeOut + "'";
return (db.rawQuery(sql, null));
}
You have to change your_table_name with your actual table name and your_time_in_out_column with actual column name and timeIn and timeOut variable type, values with your actual values.
While calling retrieveHistoryLocationFromLocalDatabase() method you need to pass 3 parameters SQLite database object, time-in and time-out.
PS: rawQuery() method is not recommended as it takes raw SQL statements as an argument. This poses SQL injection threat.

Related

Custom LIKE statement in Java Spring Data and Cassandra #Query

I need to query from a table using LIKE statement where parameters are optional.
This is custom query where I can filter employee table by which Non-Empty request param:
Select select = QueryBuilder.select().from("employee");
Where selectWhere = select.where();
if (!email.isEmpty()) {
selectWhere.and(QueryBuilder.like("email", "%" + email + "%"));
}
if (!firstName.isEmpty()) {
selectWhere.and(QueryBuilder.like("first_name", "%" + firstName + "%"));
}
//Note: User will provide either email or first_name or both.
However, the above custom query will need to manually map the Rows to the object which I find too tedious:
ResultSet rs = cassandraClient.getApplicationSession().execute( select );
return rs.all().stream().map(row -> row.getString("first_name")).collect( Collectors.toList() );
Is there a way where I can use a Query annotation like below, so it will return the entity directly?
#Query("SELECT * FROM employee WHERE email LIKE :email AND first_name LIKE :firstName")
Employee search(#Param(value="email" String email, #Param(value="firstName" String firstName)
I tried passing an empty parameter value, but I am getting the following error:
LIKE value can't be empty.

JPA named query set

I'm trying to create a namedquery with a set that changes 2 fields. Below is what I tried, which isn't working. It worked fine until I added the ae.endTime and the setParameter. Can you not SET multiple things in one query?
#NamedQuery(name = AttEnt.JQL.MARK_INCOMPLETE,
query = "UPDATE AttEnt ae"
+ " SET ae.result ="
+ " Result.INCOMPLETE,"
+ " ae.endTime = :now"
+ " WHERE ae.result IS NULL")
Below is where I'm calling the query.
final EntityManager em = emf.createEntityManager();
// Mark things with no result as incomplete and endTime to current time
em.getTransaction().begin();
final Query upAtt = em.createNamedQuery(
AttEnt.JQL.MARK_INCOMPLETE);
updateAttempts.setParameter("now", (new Date()).getTime());
upAtt.executeUpdate();
em.getTransaction().commit();
Depending on how you have mapped your endTime field, you should use an overloaded variation of the setParameter method, which add the datetime information. For example:
updateAttempts.setParameter("now", (new Date()).getTime(), TemporalType.TIME);
Here more on Temporal Types.

Pass a list of string's in IN clause in DocumentDb Query

This query works when i try to fetch records using IN and multiple Email Id's:
var families = _client.CreateDocumentQuery<Restraunt>(_documentCollection.SelfLink,
"Select Restraunt.RestrauntId from Restraunt join Rest in Restraunt.Emails where Emails.Email IN ('abc#gmail.com','ab#gmail.com') ").AsEnumerable().ToList();
I want to know how can i pass a list of Email id's as a string in the query?
I tried passing the list of strings directly but is unable to resolve that. Is there any way out to do that?
Let's say i have
List<string> elist=new List<string>{"abc#gmail.com","b#gmail.com"}
How can i pass elist in the query?
You have to change your query to use ARRAY_CONTAINS instead, i.e. like this:
Select Restraunt.RestrauntId
from Restraunt
join Rest in Restraunt.Emails
where ARRAY_CONTAINS(['abc#gmail.com','ab#gmail.com'], Emails.Email)
Then you can parameterize that query, and send the array of emails as a parameter.
You can try this:
List<string> elist=new List<string>{"abc#gmail.com","b#gmail.com"};
string emails = string.Empty;
if (eList!= null)
{
emails = "'" + string.Join("','", eList.Select(x => x != String.Empty? x :"").Distinct().ToArray()) + "'";
emails = emails.Replace("','','", "','");
}
var families = _client.CreateDocumentQuery<Restraunt>(_documentCollection.SelfLink,
"Select Restraunt.RestrauntId FROM Restraunt join Rest in Restraunt.Emails
WHERE Emails.Email IN (" + emails + ") ").AsEnumerable().ToList();

How to make case sensitive query with nodejs + pg

How to make case sensitive query with nodejs + pg
I want to select column content == 'a#gmail.com',
but it seems become select column == 'a#gmail.com'?
[error: column "a#gmail.com" does not exist]
code
var userEmail = 'a#gmail.com';
var query = 'SELECT EXISTS(SELECT * FROM "User" WHERE "Email" = "'+userEmail+'")';
dbClient.query(query, function(error, result) {
...
For use binding parameters you must number it begining with $1 (then $2 and so), then put the parameters in an Array:
var query = 'SELECT EXISTS(SELECT * FROM "User" WHERE "Email" = $1)';
dbClient.query(query, [userEmail], function(error, result) {
Always pass the parameters in an array. Is most secure.
Remember do not pass a function to query if you have a very big table unless you want to read all the table before returns the control to de function. Else you can use the "on" event or use a promise way (like https://www.npmjs.com/package/pg-promise-strict)
This doesn't have anything to do with case. The problem is that you're putting the email address in double-quotes, and in (most varieties of) SQL double-quotes indicate a column name or table name. That's why the error message says column "a#gmail.com" does not exist.
Use single-quotes around values:
var userEmail = 'a#gmail.com';
var query = 'SELECT EXISTS(SELECT * FROM "User" WHERE "Email" = \'' + userEmail + '\')';
Ideally, though, you should just use parameter binding so you don't have to worry about quoting values at all. When you use string concatenation to build SQL queries you very often open yourself up to SQL injection attacks.

Microsoft Dynamics CRM 2011 sync entities into an outside database table

I have a requirement to sync some entities (account, lead, contact etc) to a database table outside of the crm database but on the same server. I am looking for a supported way for doing this. Here's what I have tried, that don't work:
I first created table in the outside database that matches the schema from dbo.account (view). Then I wrote post create, post update, post assign and post delete plugins to create, update or delete the record in the outside table (using ADO.Net). I have written the plugin in the most generic way so that it can be registered for any entity with minimum changes to the plugin (by not hardcoding the field names). Doing it this way, the problem I am running into is with the fields that are foreign key to other tables. Eg. in dbo.account, there are fields like PrimaryContactId and PrimaryContactIdName, PreferredSystemUserId and PreferredSystemUserIdName, ParentAccountId and ParentAccountIdName etc. In the input parameters for the plugin, the xxxxId fields are available when they are updated, but not the 'xxxxIdName' fields. Because of which I am not able to 'sync' the table as is.
Is there a solution to make my plugin solution work?
Is there a better supported way for having a sync table?
Thanks in advance,
PS: 1. The data sync has to be in real time
PS: 2. Here is my function to get the query that does the update
private static string PrepareUpdateQuery(ITracingService tracingService, IEnumerable<KeyValuePair<string, object>> attributeCollection, string entityName, string entityIdName)
{
var query = "Update MainDb.MSCRM." + entityName + " set ";
foreach (KeyValuePair<string, object> keyValuePair in attributeCollection)
{
tracingService.Trace("Key: {0}", keyValuePair.Key);
if (keyValuePair.Key != entityIdName && keyValuePair.Key != "modifiedonbehalfby")
{
query = query + keyValuePair.Key + " = ";
if (keyValuePair.Value == null)
query = query + "null, ";
else
{
var typeOfValue = keyValuePair.Value.GetType().Name;
tracingService.Trace("typeOfValue: {0}", typeOfValue);
switch (typeOfValue)
{
case "EntityReference":
query = query + "'" + ((EntityReference)keyValuePair.Value).Id + "', ";
break;
case "OptionSetValue":
query = query + ((OptionSetValue)keyValuePair.Value).Value + ", ";
break;
case "BooleanManagedProperty":
query = query + (((BooleanManagedProperty)keyValuePair.Value).Value ? "1" : "0") + ", ";
break;
default:
query = query + "'" + keyValuePair.Value + "', ";
break;
}
}
}
}
return query;
}
If all you're after is the name of the entity that is an attribute on your currently executing plugin, the EntityReference object has a Name property that should contain that name. If it doesn't you you can query CRM with the id and logical name to get any value that you're looking for on the referenced entity.
Edit 1
If you're just moving the data, why even bother setting the referenced name? I'd removed those names from your database table, and just create a view that looks up the corresponding entity's name. It's what CRM is doing. It also makes your other database more normalized. IE. If you update the name of an entity that is referenced by another entity, you will have to search for and update all of those names...
the xxxIdName fields are just a helper for the views really, you can easily figure out what they
should contain.
For example, say you have an account 'some company' with a primary contact called 'bob bobson'.
when processing the account entity the primarycontactId will be a guid and the primarycontactIdName will be 'bob bobson', the accountIdName will be 'some company'.
easiest way to do this in your plugin is to look up the related entity and get the value from there - 90% of the time it's just the name field.
you also need to consider however if you are doing the right thing in using the CRM schema, perhaps it would be better to copy only the fields you need and use your own schema for the sync table.
UPDATE: just saw your code, you are overwritting the value contained in query and not setting it back to the base query, so you will get odd results/errors on the second pass through the foreach
If you're dead set on putting the related entity name in the primary entity table you can always grab it like this:
var entityEntityRef = (EntityReference)keyValuePair.Value;
var relatedEntity = service.Retrieve(entityRef.LogicalName, entityRef.Id, new ColumnSet(true));
Now relatedEntity as all the attributes available. You'll mostly be looking for the Name field, but some entities are different, like contact which uses the full name field I believe.
You can, in fact, register a single plugin for all entities (checking, of course, that the one that's firing the message is in the list of treated ones).
IEnumerable<String> supportees = new String[]{ "account", "contact" };
if(!supportees.Any(element
=> element == targetLogicalName))
return;
As for the linked entities, you have three choices.
Just skip them. Not full data sync but easies to implement.
Store the guids only. Data sync is instance-wide - limited but moderately easy.
Get all the linked data. Full information but a recursive PIA to develop.

Resources