Count query in GridGain - gridgain

Is there a count query in GridGain?
GridCacheQuery<Map.Entry<Long, Person>> qry =
queries.createSqlQuery(Person.class, "select count() from Person where street = ?");
int count = qry.execute("streetname").get();

Try SQL fields query which can select specific columns instead of the whole class:
GridCacheQuery<List<?>> qry = queries.createSqlFieldsQuery(
"select count() from Person where street = ?");
Collection<List<?>> rows = qry.execute("streetname").get();
List<?> firstRow = rows.get(0);
int count = (Integer)firstRow.get(0);

Related

How return details of updated row?

I have database in MS Access 2016, and want to run update query thru Excel VBA - this works. After this I want to return details of updated row (values from two columns - ID, Col1). Now I have only number of affected rows. How to achive this?
My query:
UPDATE
(SELECT TOP 1 ID, Col1, Update_time, Update_user
FROM Table1
WHERE Update_user Is Null
ORDER BY Col2 DESC , ID) AS U_ROW
SET U_ROW.Update_time = Now(), U_ROW.Update_user = [username];
In Excel VBA I run it thru ADODB.Command:
With baseRecordsetCommand
.ActiveConnection = objectConnection
.CommandType = adCmdStoredProc
.CommandText = "qryTest"
.NamedParameters = True
.Parameters.Append .CreateParameter("#username", adVarChar, adParamInput, 255, LCase(Environ("Username")))
.Execute recordsAffected
End With
Usually these kind of ops goes into a stored procedure but in Ms Acces/Excel you have to use VBA. Easiest way is, to retrieve the Id you are about to update before you the update.
So this comes first: save it in a variable
SELECT TOP 1 ID
FROM Table1
WHERE Update_user Is Null
ORDER BY Col2 DESC , ID
And then
update Table1
SET Table1.Update_time = Now(), Table1.Update_user = #username where Id = #idFromFirstQuery;
followed by
select * from Table1 where Id = #idFromFirstQuery;
in this way you know what Id, row you are updating.
OR:
you can turn the now() also into a parameter and supply a timestamp as parameter.
like:
update (table selection )
set update_time = '2020-19-03 10:0=10:10', update_user = 'User1';
after update you can do something like:
Select *
from Table1
where update_user = 'User1' and update_time = '2020-19-03 10:0=10:10';
NOTE!! you are highly assuming the timestamp you are supplying + username is unique. I personally would not use this method.
Not sure on this, but if you have a unique id, you could do something like this. This was done in Access, so the connection would need to be set up, as i believe this is ok.
Function sqlret() As String
Dim c As ADODB.Connection
Dim s As String
Dim r As ADODB.Recordset
Dim l As Long
Set c = CurrentProject.Connection
c.Execute "insert into tblprojects(projecttitle) values ('code1')"
Set r = New ADODB.Recordset
r.Open "select ##identity", c, 1
l = r.Fields(0).Value
r.Close
r.Open "select * from tblprojects where [projectid]=" & l, c, 1
sqlret = r.GetString
End Function

Android Studio - Kotlin - SQLite Database isn't changing the ID for one of the corresponding tables

I'm trying to implement my first SQLite Database in an Android App regarding obtaining location coordinates to keep track of where the user has been.
I'm trying to add information from my entry into two tables:
a Location table that contains information of the places name, id, latitude, and longitude information &
a CheckIn table that contains information of the places address, corresponding location_id to know which location it corresponds to, latitude, longitude, and time of check in.
Whenever I try to do this, my entry is never updated for the Locations table, solely the CheckIn table, despite using the insert() function to insert into the Locations table as well the id is not updating for the Location table.
I've went through my app in a debugger and I can't figure out what's causing the problem here, as there's no error and the program proceeds just fine to add in the necessary info for the CheckIn table.
I've tried checking StackOverFlow but I can't quite find anything that has been able to help fix my problem. If there's anyone who could help me, it'd be greatly appreciated
My add function:
fun addLoc_CheckIn(Entry: Locations)
{
val selectQuery = "SELECT * FROM $LOCATIONS ORDER BY ID"
val db = this.readableDatabase
val cursor = db.rawQuery(selectQuery, null)
var con = 0
if (cursor.moveToFirst())
{
while (cursor.moveToNext())
{
val pSLong = cursor.getDouble(cursor.getColumnIndex(SLONG))
val pCLong = cursor.getDouble(cursor.getColumnIndex(CLONG))
val pSLat = cursor.getDouble(cursor.getColumnIndex(SLAT))
val pCLat = cursor.getDouble(cursor.getColumnIndex(CLAT))
val Theta = (pCLong * Entry.cLong) + (pSLong * Entry.sLong)
var dist = (pSLat * Entry.sLat) + (pCLat * Entry.cLat * Theta)
// dist = (Math.acos(dist) * 180.00 / Math.PI) * (60 * 1.1516 * 1.609344) / 1000
dist = Math.acos(dist) * 6380000
if (dist <= 30)
{
con = 1
val db1 = this.writableDatabase
val values = ContentValues()
values.put(LOC_ID, cursor.getInt(cursor.getColumnIndex(ID)))
values.put(ADDRESS, Entry.Checks[0].Address)
values.put(LATI, Entry.Lat)
values.put(LONGI, Entry.Long)
values.put(TIME, Entry.Checks[0].Date_Time)
db1.insert(CHECKINS, null, values)
break
}
}
}
if (con == 0)
{
val db1 = this.writableDatabase
val values = ContentValues()
values.put(LOC_NAME, Entry.Name)
values.put(LAT, Entry.Lat)
values.put(LONG, Entry.Long)
values.put(CLAT, Entry.cLat)
values.put(SLAT, Entry.sLat)
values.put(CLONG, Entry.cLong)
values.put(SLONG, Entry.sLong)
Entry.Id = db1.insert(LOCATIONS, null, values)
val cvalues = ContentValues()
cvalues.put(LOC_ID, Entry.Id)
cvalues.put(ADDRESS, Entry.Checks[0].Address)
cvalues.put(LATI, Entry.Lat)
cvalues.put(LONGI, Entry.Long)
cvalues.put(TIME, Entry.Checks[0].Date_Time)
db1.insert(CHECKINS, null, cvalues)
}
}
My OnCreate function with the corresponding companion object:
companion object {
private val DATABASE_NAME = "LocationsDB"
private val DATABASE_VERSION = 1
// 1st Table - Unique Check Ins
private val LOCATIONS = "LOCATIONS"
private val ID = "ID"
private val LOC_NAME = "LOC NAME"
private val LAT = "LAT"
private val LONG = "LONG"
private val CLAT = "CLAT"
private val SLAT = "SLAT"
private val CLONG = "CLONG"
private val SLONG = "SLONG"
// 2nd Table - Repeated Check Ins
private val CHECKINS = "CHECKINS"
private val CHECKIN_ID = "CHECKIN_ID"
private val LOC_ID = "LOC_ID"
private val ADDRESS = "ADDRESS"
private val TIME = "TIME"
private val LATI = "LAT"
private val LONGI = "LONG"
}
override fun onCreate(p0: SQLiteDatabase?) {
val LOCATION_QUERY = "CREATE TABLE " + LOCATIONS + "(" + ID +
" INTEGER PRIMARY KEY AUTOINCREMENT, " + LOC_NAME +
" TEXT, " + LAT + " INTEGER, " + LONG + " INTEGER, " +
CLAT + " INTEGER, "+ SLAT + " INTEGER, " + CLONG + " INTEGER, "+ SLONG + " INTEGER " + ")"
val CHECKIN_QUERY = "CREATE TABLE " + CHECKINS + "(" +
LOC_ID + " INTEGER, " + CHECKIN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + LATI + " INTEGER, " + LONGI + " INTEGER, " + ADDRESS +
" TEXT, " + TIME + " TEXT " + ")"
p0!!.execSQL(LOCATION_QUERY)
p0.execSQL(CHECKIN_QUERY)
}
Now, in my constructor for the Location class and the CheckIns class, I have the id's set to -1, which is what the id for the location remains, even after using the insert() function. Now, this doesn't cause me any issues with regards to adding in my CheckIns as well incrementing the ids in my CheckIns table and I doubt it's causing an issue but I figured it'd be best to include the information, just in case.
I believe that you have an issue with the name of the column due to using
private val LOC_NAME = "LOC NAME"
A column name cannot have a space unless it is enclosed in special characters as per SQL As Understood By SQLite - SQLite Keywords.
This isn't an issue when the table is create (the column name will be LOC). However, when you attempt to insert you will get a syntax error, the row will not be inserted but as you are using the SQLiteDatabase insert method, the error is trapped and processing continues.
However, in the log you would see something similar to :-
2019-10-29 15:47:35.119 12189-12189/aso.so58600930insert E/SQLiteLog: (1) near "NAME": syntax error
2019-10-29 15:47:35.121 12189-12189/aso.so58600930insert E/SQLiteDatabase: Error inserting LOC NAME=MyLoc LAT=100 CLAT=120 LONG=110 SLAT=140 CLONG=130 SLONG=150
android.database.sqlite.SQLiteException: near "NAME": syntax error (code 1 SQLITE_ERROR): , while compiling: INSERT INTO LOCATIONS(LOC NAME,LAT,CLAT,LONG,SLAT,CLONG,SLONG) VALUES (?,?,?,?,?,?,?)
You could circumvent the above by using :-
val db1 = this.writableDatabase
val values = ContentValues()
values.put("LOC", Entry.Name)
values.put(LAT, Entry.Lat)
values.put(LONG, Entry.Long)
values.put(CLAT, Entry.cLat)
values.put(SLAT, Entry.sLat)
values.put(CLONG, Entry.cLong)
values.put(SLONG, Entry.sLong)
Entry.Id = db1.insert(LOCATIONS, null, values)
However, it is not suggested that you use the above BUT that instead you correct the name, e.g. using :-
private val LOC_NAME = "LOC_NAME"
then clear the App's data or uninstall the App and then rerun the App.
This fix assumes that you are developing the App and can afford to lose any existing data. You could retain data but this is a little more complicated as you basically have to create a new table with the appropriate column name, copy the data from the original table, rename or drop the original table and then rename the new table to be the original name.

How to get table names from Presto query using presto-parser?

Not able to extract table names used within with clause, I'm using presto-parser version 0.226.
SqlParser sqlParser = new SqlParser();
String sql = "WITH dataset AS ( SELECT ROW('Bob', 38) AS users from tabb ) SELECT * FROM dataset";
Query query = (Query)sqlParser.createStatement(sql, ParsingOptions.builder().build());
QuerySpecification body = (QuerySpecification)query.getQueryBody();
System.out.println("From = " + body.getFrom().get());
/* Output
From = Table{dataset}
*/
Expected output
From = Table{dataset, tabb}

AutoQuery/OrmLite incorrect total value when using joins

I have this autoquery implementation
var q = AutoQuery.CreateQuery(request, base.Request).SelectDistinct();
var results = Db.Select<ProductDto>(q);
return new QueryResponse<ProductDto>
{
Offset = q.Offset.GetValueOrDefault(0),
Total = (int)Db.Count(q),
Results = results
};
The request has some joins:
public class ProductSearchRequest : QueryDb<GardnerRecord, ProductDto>
, ILeftJoin<GardnerRecord, RecordToBicCode>, ILeftJoin<RecordToBicCode, GardnerBicCode>
{
}
The records gets returned correctly but the total is wrong. I can see 40,000 records in database but it tells me there is 90,000. There is multiple RecordToBicCode for each GardnerRecord so it's giving me the number of records multiplied by the number of RecordToBicCode.
How do I match the total to the number of GardnerRecord matching the query?
I am using PostgreSQL so need the count statement to be like
select count(distinct r.id) from gardner_record r etc...
Dores OrmLite have a way to do this?
I tried:
var q2 = q;
q2.SelectExpression = "select count(distinct \"gardner_record\".\"id\")";
q2.OrderByExpression = null;
var count = Db.Select<int>(q2);
But I get object reference not set error.
AutoQuery is returning the correct total count for your query of which has left joins so will naturally return more results then the original source table.
You can perform a Distinct count with:
Total = Db.Scalar<long>(q.Select(x => Sql.CountDistinct(x.Id));

How to insert data in mysql database using C#

string query2 = "INSERT INTO library_database.status_of_issue VALUES('";
query2 = query2 +textBox2.Text + "','";
query2 = query2 + textBox1.Text + "', CURDATE(),ADDDATE(CURDATE(), INTERVAL 14 DAY)";
cmd = new MySqlCommand(query2, con);
MySqlDataReader d1 = cmd.ExecuteReader();
MessageBox.Show("Issed...");
d1.Close();
Missing the closing parenthesys for the VALUES clause, but your query should be rewritten to avoid Sql Injection and an INSERT query is executed with ExecuteNonQuery
string query2 = #"INSERT INTO library_database.status_of_issue VALUES(#p1, #p2,
CURDATE(),ADDDATE(CURDATE(), INTERVAL 14 DAY))";
cmd = new MySqlCommand(query2, con);
cmd.Parameters.AddWithValue("#p1", textBox2.Text);
cmd.Parameters.AddWithValue("#p2", textBox1.Text);
int rows = cmd.ExecuteNonQuery();
if(rows > 0)
MessageBox.Show("insert OK...");
So very obvious. You're missing the ending paranthesis of VALUES. This should work:
string query2 = string.Format("INSERT INTO library_database.status_of_issue VALUES('{0}', '{1}', CURDATE(), ADDDATE(CURDATE(), INTERVAL 14 DAY))", textBox2.Text, textBox1.Text);
using(var cmd = new MySqlCommand(query2, con))
{
if(cmd.ExecuteNonQuery() > 0)
MessageBox.Show("Issed...");
}
Also note that INSERT, UPDATE and DELETE commands should be executed using ExecuteNonQuery().

Resources