getting values from sqlite using group by null pointer - sqlite

I have a table in that I have some duplicate record now I am getting the record without excluding duplicate records. I want to get all record excluding duplicate, and from duplicate data I want only one record. like if I have three same records i want only one record.
my query is like,this giving null pointer.
Cursor dCursor=database.rawQuery( "SELECT FROM note_image GROUP BY IDMATCHER",null,null);
and if I want to get this using query() method how can I do that. I am getting all records by using this method. but I want all records only once. without occurrence two time a record.
public Cursor fetchImage(){
String[] columns = new String[]{DatabaseHelper.NOTE_IMG_ID,DatabaseHelper.NOTE_HD_IMG_PATH,DatabaseHelper.NOTE_IMG_PATH_THUMB,DatabaseHelper.TEMP_IMG_ID};
Cursor cursor=database.query(DatabaseHelper.TABLE_NOTE_IMAGE,columns,null,null,null,null,null);
if (cursor!=null){
cursor.moveToNext();
}
return cursor;
}

I done using this query. taken help from above commented link. ` public Cursor fetchImage() {
Cursor icursor = database.query(true, DatabaseHelper.TABLE_NOTE_IMAGE, new String[]
{DatabaseHelper.TEMP_IMG_ID, DatabaseHelper.NOTE_IMG_PATH_THUMB},
null, null, DatabaseHelper.TEMP_IMG_ID, null, null, null);
if (icursor != null) {
icursor.moveToNext();
}
return icursor;
}`

Related

Why is this query forming an incorrect foreign key constraint in Knex/SQLite3?

The Goal
I am trying to make two tables, `users` and `clients`, wherein `clients` has a foreign key called `userId` that references the `id` primary key of `users`.
Shows the desired relationship between the tables users and clients
The Migrations
Users
exports.up = function(knex) {
return knex.schema
.createTable('users', function (table) {
table.increments().primary();
table.string('username').unique().notNullable();
table.string('email').unique().notNullable();
table.string('password').notNullable();
table.boolean('admin').notNullable().defaultTo(false);
});
};
Clients
I have tried a variety of different variations of this, which I will show here along with their results:
exports.up = function(knex) {
return knex.schema
.createTable('clients', function (table) {
table.increments().primary();
table.string('name').notNullable();
table.string('secret').notNullable();
table.integer('userId').unsigned().references("id").inTable("users").onDelete("CASCADE");
});
};
This resulted the successful creation of the database, however, the SQLite Viewer indicated that clients.id was somehow referencing a users.userId, as shown in the following image.
exports.up = function(knex) {
return knex.schema
.createTable('clients', function (table) {
table.increments().primary();
table.string('name').notNullable();
table.integer('userId').unsigned();
table.string('secret').notNullable();
table.foreign('userId').references("users.id").onDelete("CASCADE");
});
};
This produced the exact same result as the previous code.
What am I doing wrong?
Edit: An Additional Complicating Factor
I have tried swapping `userId` and `id` in the first attempt at making the clients table. While this did appear to work for the clients table, when I tried to do the same for a `codes` table, I encountered an error that seemed to indicate swapping the two wasn't doing what I hoped it would do. This is consistent with what I've seen in tutorials. I'm inclined to think I was closer to the correct answer at the beginning.
exports.up = function(knex) {
return knex.schema
.createTable('codes', function (table) {
table.string('value').notNullable();
table.string('redirectUri').notNullable();
table.integer('userId').unsigned();
table.integer('clientId').notNullable();
table.foreign('id').references("userId").inTable("users").onDelete("CASCADE");
});
};
Error: create table codes (value varchar(255) not null, redirectUri varchar(255) not null, userId integer, clientId integer not null, foreign key(id) references users(userId) on delete CASCADE) - SQLITE_ERROR: unknown column "id" in foreign key definition

How to insert into a table with ONLY an Auto-Increment column

I have a table the only has an Id column in SQL. It is an Auto-Increment column. It is used to keep track of a booking number sequence to be sent to an outside system. In SQL I use this to insert a new record:
insert into bookingnumbers default values
I would like to use entity framework and get the Next available Id. I have tried this:
private async Task<long> GetNextBookingNumberAsync()
{
BookingNumbers bookingNumber = default;
GhanemContext.BookingNumbers.Add(bookingNumber);
await GhanemContext.SaveChangesAsync();
return bookingNumber.Id;
}
However, booking number is just null and I get:
ArgumentNullException: Value cannot be null. Parameter name: entity
Any help would be greatly appreciated!

DynamoDb - .NET Object Persistence Model - LoadAsync does not apply ScanCondition

I am fairly new in this realm and any help is appreciated
I have a table in Dynamodb database named Tenant as below:
"TenantId" is the hash primary key and I have no other keys. And I have a field named "IsDeleted" which is boolean
Table Structure
I am trying to run a query to get the record with specified "TenantId" while it is not deleted ("IsDeleted == 0")
I can get a correct result by running the following code: (returns 0 item)
var filter = new QueryFilter("TenantId", QueryOperator.Equal, "2235ed82-41ec-42b2-bd1c-d94fba2cf9cc");
filter.AddCondition("IsDeleted", QueryOperator.Equal, 0);
var dbTenant = await
_genericRepository.FromQueryAsync(new QueryOperationConfig
{
Filter = filter
}).GetRemainingAsync();
But no luck when I try to get it with following code snippet (It returns the item which is also deleted) (returns 1 item)
var queryFilter = new List<ScanCondition>();
var scanCondition = new ScanCondition("IsDeleted", ScanOperator.Equal, new object[]{0});
queryFilter.Add(scanCondition);
var dbTenant2 = await
_genericRepository.LoadAsync("2235ed82-41ec-42b2-bd1c-d94fba2cf9cc", new DynamoDBOperationConfig
{
QueryFilter = queryFilter,
ConditionalOperator = ConditionalOperatorValues.And
});
Any Idea why ScanCondition has no effect?
Later I also tried this: (throw exception)
var dbTenant2 = await
_genericRepository.QueryAsync("2235ed82-41ec-42b2-bd1c-d94fba2cf9cc", new DynamoDBOperationConfig()
{
QueryFilter = new List<ScanCondition>()
{
new ScanCondition("IsDeleted", ScanOperator.Equal, 0)
}
}).GetRemainingAsync();
It throws with: "Message": "Must have one range key or a GSI index defined for the table Tenants"
Why does it complain about Range key or Index? I'm calling
public AsyncSearch<T> QueryAsync<T>(object hashKeyValue, DynamoDBOperationConfig operationConfig = null);
You simply cant query a table only giving a single primary key (only hash key). Because there is one and only one item for that primary key. The result of the Query would be that still that single item, which is actually Load operation not Query. You can only query if you have composite primary key in this case (Hash (TenantID) and Range Key) or GSI (which doesn't impose key uniqueness therefore accepts duplicate keys on index).
The second code attempts to filter the Load. DynamoDBOperationConfig's QueryFilter has a description ...
// Summary:
// Query filter for the Query operation operation. Evaluates the query results and
// returns only the matching values. If you specify more than one condition, then
// by default all of the conditions must evaluate to true. To match only some conditions,
// set ConditionalOperator to Or. Note: Conditions must be against non-key properties.
So works only with Query operations
Edit: So after reading your comments on this...
I dont think there conditional expressions are for read operations. AWS documents indicates they are for put or update operations. However, not being entirely sure on this since I never needed to do a conditional Load. There is no such thing like CheckIfExists functionality as well in general. You have to read the item and see if it exists. Conditional load will still consume read throughput so your only advantage would be only NOT retrieving it in other words saving the bandwith (which is very negligible for single item).
My suggestion is read it and filter it in your application layer. Dont query for it. However what you can also do is if you very need it you can use TenantId as hashkey and isDeleted for range key. If you do so, you always have to query when you wanna get a tenant. With the query you can set rangeKey(isDeleted) to 0 or 1. This isnt how I would do it. As I said, would just read it and filter it at my application.
Another suggestion thing could be setting a GSI on isDeleted field and writing null when it is 0. This way you can only see that attribute in your table when its only 1. GSI on such attribute is called sparse index. Later if you need to get all the tenants that are deleted (isDeleted=1) you can simply scan that entire index without conditions. When you are writing null when its 0 dynamoDB wont put it in the index at the first place.

Which rows were deleted? [duplicate]

I need to run two statements like so:
Select amount from db where ID=5
DELETE from db where ID=5
Currently I prepare and run two different statements. I wonder if there is a way to combine it in one statement.
Basically all I need to do is to get an amount column from the row before it is deleted.
SQLite does not support this extension to standard SQL -- you do have to use both statements, SELECT first, DELETE next. You can wrap them in a transaction, of course, (BEGIN and COMMIT statements before and after will guarantee that), to guarantee atomicity and consistency.
If you just want to select rows and delete them in one pass, you can use the returning clause in the delete statement.
For instance:
delete from myTable returning *
The delete statement has all select functionalities possible such as with and where that permits to select rows with any logic.
Assuming that your calling thread/process has a unique identifier (e.g. thread_id), I think a viable approach would be to add a flag (say, "handlerid") to your table, which is set to null on insert, and then do:
update db set handlerid = <my_thread_id> where handlerid is null;
select * from db where handlerid is not null and handlerid = <my_thread_id>;
delete from db where handlerid is not null and handlerid = <my_thread_id>;
Not sure how it would perform vs a transaction but can't think of any reason it would be materially worse (might even be better), and using this approach the code seems about as straightforward as you can get. unlike a transaction, it won't require you to loop in the case that a transaction fails, in order to be sure that all outstanding elements that were in the table at the time of the most recent SELECT got processed.
It's late but for future visitor. In my case I did like below
I want to delete that ID where amount = 5 so I did this
public void selectAndDelete() {
try {
SQLiteDatabase db = this.getWritableDatabase();
int i=db.delete(table_name, "ID = (select ID from table_name where amount = 5)", null);
if(i>0)
{
// I'm inserting here new record
}
} catch (SQLException e) {
}
}
So, In your case you need to modify where condition like you want
You can do this by separating the two statements with a semicolon, e.g. (using the .NET port of SQLite):
using (SQLiteConnection conn = new SQLiteConnection("Data Source=fie.db3"))
{
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT id FROM fies; DELETE FROM fies WHERE id = 5;";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader[0]);
}
}
}
}

windows service for data insertion

I have created windows service for data-insertion.Time interval is one min.After one min, data insert into table.Data get inserted into table at multiple time.I don't want to that,only one time.How to do that?May I need to check in database wether entry is there or nor if not add.
You can use this query before inserting the data.
IF EXISTS(SELECT * FROM dbo.YourTable WHERE Name = #Name)
RETURN
-- here, after the check, do the INSERT
You might also want to create a UNIQUE INDEX on your Name column to make sure no two rows with the same value exist:
CREATE UNIQUE NONCLUSTERED INDEX UIX_Name
ON dbo.YourTable(Name)
Hope this help you.
//You can do like this in ur code
if (ChkRecordExist() == true)
{
//Do nothing
}
else
{
// insert operation
}
protected bool ChkRecordExist()
{
//here logic for record exist or not.
//if record is exist return true else return false
}

Resources