Sqlite Query can't get 100% - sqlite

public Cursor getStatsPercent(String startdate, String enddate) {
String query = "SELECT *, ROUND((count(sex)*100)/(SELECT count(sex) FROM salesTable)) AS '"+PERCENTAGE+"' FROM salesTable where timeStamp BETWEEN '"+startdate+"' AND '"+enddate+"' GROUP BY sex ORDER BY percentage DESC" ;
Cursor c = dbSales.rawQuery(query, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
Everything works fine but i always get back a Value under 100%.
I think it has to do with the ROUND but couldn't fix this.

public Cursor getStatsPercent(String startdate, String enddate) {
String query = "SELECT *, ROUND((count(sex)*100.0)/(SELECT count(sex) FROM salesTable)) AS '"+PERCENTAGE+"' FROM salesTable where timeStamp BETWEEN '"+startdate+"' AND '"+enddate+"' GROUP BY sex ORDER BY percentage DESC" ;
Cursor c = dbSales.rawQuery(query, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
I fixed it, just changed *100 to *100.0
So if anyone wants to calculate the percentage of the values from the database between dates this code should work.

Related

Cursor inside another cursor in sqlite db

I have the below code where I am using nested cursors. Both of them are not null but I am getting error
"android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0" on the inner cursor.
Cursor cursor3 = null;
Cursor cursor2 = db.getAllFriendsChat();
cursor2.moveToFirst();
while (!cursor2.isAfterLast()) {
String number = cursor2.getString(cursor2.getColumnIndexOrThrow(ChatModel.COLUMN_CHAT_SENT_TO));
cursor3 = db.getName(number);
String name = cursor3.getString(cursor3.getColumnIndexOrThrow(db.KEY_NAME));
db.insertList(name, number);
cursor3.close();
cursor2.moveToNext();
}
cursor2.close();
getName() Method:
public Cursor getName(String phone) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("select * from " + TABLE_STUDENTS + " where phone_number = " + phone, null);
if (c != null) {
c.moveToFirst(); //***I see that this statement is executed.***
}
return c;
}
I am unable to understand where I am doing mistake. Is there a different way to handle nested cursors in sqlite db. Pls help.
Thanks !
rawQuery() never returns null.
To test whether a cursor is empty, you have to check whether moveToFirst() succeeds, or call isAfterLast().

Wrong query: Incorrect syntax near ')'

I have ASP.NET application and we use Dapper library. The code that produces the error looks as following:
public bool CheckIfExists(IEnumerable<long> ticketGroups, long dateId, int userId)
{
bool bRetVal = false;
string sql = "if exists (select * from T_TicketGroupsToChangePrice where SubTypeId = #SubTypeId and DateId = #dateId and UserId = #userId)";
using (var conn = CreateSqlConnection())
try
{
int rows = conn.Execute(sql, ticketGroups.Select(g => new { SubTypeId = g, UserId = userId, dateId }));
if (rows > 0)
bRetVal = true;
}
catch (SqlException ex)
{
throw new Exception("Error", ex);
}
return bRetVal;
}
When I run the application it throws the exeption: Incorrect syntax near ')'
As you can see, there can be more tickets (IEnumerable type) with the same date and user.
I'm not sure what's going on.
That is because it is not valid SQL to start with an if (If you mean to use T-SQL it is, but then you have to write the entire if statement)
I think a simple case is what you need:
select case
when exists (select * from T_TicketGroupsToChangePrice where SubTypeId = #SubTypeId and DateId = #dateId and UserId = #userId)
then 1
else 0
end
Your query "if exists (select * from T_TicketGroupsToChangePrice where SubTypeId = #SubTypeId and DateId = #dateId and UserId = #userId)" return some data if the table have some so for that it require something to work on. Like if else condition in programming we can modify this as :
if exists
(select * from T_TicketGroupsToChangePrice where SubTypeId = #SubTypeId and DateId = #dateId and UserId = #userId)
Print 'Have Data'
else
Print 'Don't Have data'
Rewriting your code :
public bool CheckIfExists(IEnumerable<long> ticketGroups, long dateId, int userId)
{
bool bRetVal = false;
string sql = "if exists (select * from T_TicketGroupsToChangePrice where SubTypeId = #SubTypeId and DateId = #dateId and UserId = #userId) Print '**your code to execute if exist data**' else Print '**your code to execute if doesnot exist data**'";
using (var conn = CreateSqlConnection())
try
{
int rows = conn.Execute(sql, ticketGroups.Select(g => new { SubTypeId = g, UserId = userId, DateId = dateId }));
if (rows > 0)
bRetVal = true;
}
catch (SqlException ex)
{
throw new Exception("Error", ex);
}
return bRetVal;
}
this link will help you more :
https://dba.stackexchange.com/questions/30159/exist-select-from-my-table
If your result depends on the number of rows and not on what's returned from the SQL, you could try this:
if exists ([whatever]) select 1
This works, because if there are no matching values, no recordset is returned, and your affected record count is zero.
You could also try something a bit simpler:
select 1
from T_TicketGroupsToChangePrice
where SubTypeId = #SubTypeId
and DateId = #dateId
and UserId = #userId;
But that has the disadvantage of returning one row for however many records you have. This could be a lot, depending on the app and the context, and in any case you don't want to pull over data that you're not going to use.
I wouldn't recommend a CASE statement, because SELECT CASE EXISTS ([whatever]) THEN 1 END will still return one record, and your affected record count will be 1 even if no records exist.
The problem with your original SQL, by the way: The statement is incomplete. You're saying "if exists ..." but you never finish it with the equivalent of a "then". You need to say "if exists() select 1" or something similar.

How to check table is empty with count(*)

I am trying to check if a table is empty. I code this method:
public boolean checkIfNULL()
throws SQLException, ClassNotFoundException {
boolean flag=false;
System.out.println("Checking if table is empty...");
String sq = "select count(*) from TABLE1";
try {
Class.forName(typeDB);
c = DriverManager.getConnection(path);
stm = c.prepareStatement(sq);
PreparedStatement stm = c.prepareStatement(sq);
int rowsAffected = stm.executeUpdate();
if(rowsAffected == 0)
flag=true;
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (stm != null) {
stm.close();
}
if (c != null) {
c.close();
}
}
return flag;
}
but sth wrong is hapenning and I get an error message
Query returns results
Exceptionn: java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (Connection is closed)
How I check the returning value of check?
UPDATE 1:
Instead of the query above, I tried also SELECT EXISTS(SELECT 1 FROM TABLE1)
but the same is happening..
UPDATE 2:
I used this:
ResultSet rs = stm.executeQuery();
if(!rs.next())
flag=true;
else
System.err.println("ERROR - The table has records...");
and it prints the ERROR - "The table has records...". How is this possible? I see the table through SQLite manager and it is empty!
You are executing a SELECT, so you need to use executeQuery, not executeUpdate. executeUpdate is for statements like UPDATE, DELETE and INSERT, executeQuery is for executing statements that return a result set (like SELECT).
You need to execute a select statement, and do:
try (ResultSet rs = stm.executeQuery()) {
rs.next(); // You always have a row, with the count
int count = rs.getInt(1);
flag = count == 0;
}
The code in your update won't work, because if you do a SELECT count(*) FROM table, then you always have one row (with the count).

Sqlite Row Number

I have problem with my database row number. My table has 3 columns(ROWID,WORD,DEFINITION) and 3 row. I delete second row and then I try to query same row, my app fails. is this an autoincrement problem? what should I do?
Here is my code;
//Get that function
public String getThat(int id) {
String result= "";
String[] columns = new String[]{KEY_ROWID,KEY_WORD,KEY_DEFINITION};
Cursor c = ourDatabase.query(DB_TABLE, columns, KEY_ROWID +
"=" + id, null, null, null, null,null);
if(c!=null){
c.moveToFirst();
}
result = c.getString(c.getColumnIndex(KEY_DEFINITION));
return result;
}
//delete function
public boolean deleteRecords(long rowId){
return ourDatabase.delete(DB_TABLE, KEY_ROWID +"="+rowId,null)>0;
}
When the query doesn't match anything, a non-null Cursor is returned anyway but it doesn't contain any rows. When you try to access data from a non-existing row an exception is thrown.
Change this
if(c!=null){
c.moveToFirst();
}
result = c.getString(c.getColumnIndex(KEY_DEFINITION));
to something like
if(c.moveToFirst()){
result = c.getString(c.getColumnIndex(KEY_DEFINITION));
}
i.e. check the return value of moveTo..() and only access cursor data if the move succeeded and the cursor points to a valid row.

Sqlite trigger in android with an update

When I am trying to achieve is a trigger that will update a table when an insert is made that should if the table has the articleId in place already the articleIsLiked should be changed to 0 and if not it should insert the articleId and the articleIsLiked to 1. Currently when I make an insert a new record is made each time I try to run an insert query instead of updating the record.
CREATE TRIGGER test_update
AFTER INSERT ON articlesTable
BEGIN
INSERT INTO articlesTable ( articleId, articleIsLiked)
VALUES(NEW.articleId, 1) ON DUPLICATE KEY UPDATE
articleIsLiked = 0;
END;
articlesTable
id PK
articleId int
articleIsLiked int
You cannot change an INSERT into an UPDATE with a trigger.
The easiest way to do this is in your code:
db.beginTransaction();
try {
ContentValues cv = new ContentValues();
long c = DatabaseUtils.queryNumEntries(db, "articlesTable",
"articleId = " + id);
if (c > 0) {
cv.put("articleIsLiked", 0);
db.update("articlesTable", cv, ""articleId = " + id, null);
} else {
cv.put("articleId", id);
cv.put("articleIsLiked", 1);
db.insert("articlesTable", null, cv);
}
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}

Resources