How to find value in a set in SQLite [duplicate] - sqlite

In Mysql, FIND_IN_SET is used to find value in a set. I have tried FIND_IN_SET in SQLite, but it is not an SQL keyword. I have Googled, but I did not get an answer. If anybody knows, please tell me the alternative to FIND_IN_SET in SQLite.

If you need just a true / false value rather than index then you can use LIKE clause:
(',' || column_name || ',') LIKE '%,value,%'

we can write query like change into hibernate critearea
my old query
select * FROM game_detail WHERE content_id=176 and FIND_IN_SET(12,group_master_id)
New query
select *
FROM game_detail
WHERE content_id=176
and (group_master_id LIKE '%12,%'|| group_master_id LIKE '%,12,'|| group_master_id LIKE '%12')

This is my old query
String query = "SELECT a.content_id,a.content_name,a.image_name,a.image_path,a.rating,d.content_type_name"
+ "from content_master a, category_content_mapping b, "
+ "game_detail c, content_type_master d "
+ "where a.content_id=b.content_id "
+ "and c.content_id = a.content_id "
+ "and a.content_type_id = d.content_type_id "
+ "and b.category_id = '" + category_id + "' "
+ "and find_in_set('" + group_master_id + "',c.group_master_id) "
+ "and a.is_active='Y' and b.is_active = 'Y' and c.is_active = 'Y'"
+ "order by b.content_mapping_id DESC limit 0,3";
Criteria in hibernate use like alternate of find_in_set
Session session=new Configuration().configure().buildSessionFactory().openSession();
Criteria criteria=session.createCriteria(ContentMaster.class);
criteria.setFetchMode("CategoryContentMapping", FetchMode.JOIN);
criteria.setFetchMode("GameDetail", FetchMode.JOIN);
criteria.createAlias("categoryContentMappings","cat");
criteria.createAlias("contentTypeMaster", "ctm");
criteria.createAlias("gameDetails","game");
criteria.add(Restrictions.eq("cat.categoryMaster.categoryMasterId", 9));
criteria.add(Restrictions.disjunction()
.add(Restrictions.like("game.groupMasterId","%12,%"))
.add(Restrictions.like("game.groupMasterId","%,12,%"))
.add(Restrictions.like("game.groupMasterId","%12%")));
criteria.add(Restrictions.eq("isActive", "y"));
criteria.add(Restrictions.eq("cat.isActive", "y"));
criteria.add(Restrictions.eq("ctm.isActive", "y"));
criteria.addOrder(Order.desc("cat.contentMappingId"));

Related

How do I refine this SOQL query in Retool?

I am trying to restrict the output here to a specific account type, but I'm not sure how I add that AND clause. The Retool has a search for account name, and a selector for country - but I only want to pull out Type = 'Indirect Reseller' - just struggling to make that work as my SQL knowledge isn't good enough.
SELECT
Name,
Description,
NumberOfEmployees,
AnnualRevenue,
Industry,
Website,
OwnerId,
BillingCountry,
BillingCountryCode,
Type,
ID
FROM Account
{{search.value == "" ? (select_industry.value['0'] == null ? '' : " WHERE ( BillingCountryCode LIKE " + "'" + select_industry.value.join("' OR BillingCountryCode LIKE '") + "')") : " WHERE ( Name LIKE " + "'%" + search.value + "%'" + " OR Website LIKE " + "'%" + search.value + "%'" + ")" + (select_industry.value['0'] == null ? '' : " AND ( BillingCountryCode LIKE " + "'" + select_industry.value.join("' OR BillingCountryCode LIKE '") + "')")}}
This works, but I want to limit to Indirect Reseller account types

android.database.sqlite.SQLiteException: no such column error even if column exists

I know this question has been asked multiple times, but there is something wrong in my syntax and I can't figure out what. This is the method that adds my column:
Property declaration:
public static final String COLUMN_TS_MILIS = "ts_milis";
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_PRODUCT + " TEXT, " +
COLUMN_PRICE + " TEXT, " +
COLUMN_TS + " TIMESTAMP DEFAULT CURRENT_TIMESTAMP," +
COLUMN_TS_MILIS + "timestamp integer default (cast(strftime('%s', 'now') as int))" +
");";
db.execSQL(query);
and this is the query that triggers the error:
Cursor totalCof = db.rawQuery("SELECT sum(" + COLUMN_PRICE + ")" + " FROM " + TABLE_NAME
+ " WHERE " + COLUMN_TS_MILIS + "= date('now')", null);
What is wrong in my syntax? Many thanks for help!
For the column that is meant to be named as per COLUMN_TS_MILIS, have omitted a space between the column name and the column type and hence the column name is a concatenation of the column name and column type. So assuming COLUMN_TS_MILIS resolves to millis then the QL will be :-
`CREATE TABLE ......,millistimestamp integer default (cast(strftime('%s', 'now') as int))`
instead of
`CREATE TABLE ......,millis timestamp integer default (cast(strftime('%s', 'now') as int))`
Additionally you have specified two types, timestamp and also integer, this won't be an issue SQLIite wise but may lead to confusion.
As such you probably just want
`CREATE TABLE ......,millis integer default (cast(strftime('%s', 'now') as int))`
As such you probably want to use :-
String query = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY, " +
COLUMN_PRODUCT + " TEXT, " +
COLUMN_PRICE + " TEXT, " +
COLUMN_TS + " TIMESTAMP DEFAULT CURRENT_TIMESTAMP," +
COLUMN_TS_MILIS + " INTEGER DEFAULT (cast(strftime('%s', 'now') as int))" +
");";
Note AUTOINCREMENT has been removed as you almost certainly don't need it as it has overheads.
To implement the change, you would have to drop the table, as it exists. The easiest way to do this is to either :-
delete the App's data or
uninstall the App
and then rerun the App (assuming that existing, if any, data can be lost).

SQLiteException: near "t": syntax error (code 1):

I'm receiving the following error from my insert db call.
"android.database.sqlite.SQLiteException: near "t": syntax error (code 1): , while compiling: INSERT INTO OCR(bmp, title, description) VALUES ('[B#9430d52', 'Result:', '
pacifism
Enchant creature
Creature can't attack Or
That
—Knrtce of Qal Sima
');
This is my insert statement
String INSERT_TO_DB = "INSERT INTO " + TABLE_NAME + " ("+
COLUMN_BITMAP + ", " +
COLUMN_TITLE + ", " +
COLUMN_DESCRIPTION +") " +
"VALUES ('" + getBytes(ocr.getBitmap()) + "', '" + ocr.getTitle() + "', '" + ocr.getDescription() + "');";
db.execSQL(INSERT_TO_DB);
The thing is it was working on other images, i'm thinking it has something to do with the fact that there's a lot of "/n" in the description it's trying to insert into the db.
Never put string values directly into an SQL statement; use parameters instead.
It is not necessary to use a prepared statement object to achieve this:
db.execSQL("INSERT ... VALUES(?, ?, ?)",
new Object[]{ ocr.getTitle(), ... });
And there is a helper function that constructs the statement for you, and handles binary data correctly:
ContentValues cv = new ContentValues();
cv.put(COLUMN_TITLE, ocr.getTitle());
cv.put(COLUMN_BITMAP, ocr.getBitmap()); // byte array
...
db.insert(TABLE_NAME, null, cv);

How to set dynamically the correct Dateformat in VB for SQL Query

Hello i have an sql query which uses a Dateformat. This code will run on different servers but every server have different dateformats. sometimes yyyy-MM-dd and sometimes yyyy-dd-MM.
I tried to read the userlanguage to choose the correct query. but it doesnt work properly.
Do you know any other good solution to solve my problem ?
Thanks in advance
Dim Systemsprache as String
Systemsprache = Request.UserLanguages(0)
If String.Compare(Systemsprache, "de-DE") = 0 Then
sqlcmd = "SELECT convert(varchar(8) , [VON],108) as [VON] ,convert(varchar(8) , [BIS],108) as [BIS] FROM [RESERVIERUNGRAUM] where RAUM_ID =" + hCurrRaumID.Value + " and VON >='" + Date.Parse(wiDateVON1.Value).ToString("yyyy-MM-dd") + "' and BIS <'" + Date.Parse(wiDateVON1.Value).AddDays(1).ToString("yyyy-MM-dd") + "'"
Else
sqlcmd = "SELECT convert(varchar(8) , [VON],108) as [VON] ,convert(varchar(8) , [BIS],108) as [BIS] FROM [RESERVIERUNGRAUM] where RAUM_ID =" + hCurrRaumID.Value + " and VON >='" + Date.Parse(wiDateVON1.Value).ToString("yyyy-dd-MM") + "' and BIS <'" + Date.Parse(wiDateVON1.Value).AddDays(1).ToString("yyyy-dd-MM") + "'"
End If
If I remember correctly, you can use the universal format '#yyyy-mm-dd#' regardless of the server default date format.

Python: infinite loop while executing SQLite statement

I have this 2 SQLite scripts:
both tested by direct input into SQLite.
def getOutgoingLinks(self, hostname):
t = (hostname,)
result = self.__cursor.execute("SELECT url.id, hostname.name, url.path, linking_to.keyword, siteId.id " +
"FROM url, hostname, linking_to, " +
"(SELECT url.id FROM url, hostname " +
"WHERE hostname.name = (?) " +
"AND hostname.id = url.hostname_id " +
") AS siteId " +
"WHERE linking_to.from_id = siteId.id " +
"AND linking_to.to_id = url.id " +
"AND url.hostname_id = hostname.id", t)
result = result.fetchall()
return result
def getIncommingLinks(self, hostname):
t = (hostname,)
result = self.__cursor.execute("SELECT url.id, hostname.name, url.path, linking_to.keyword, siteId.id " +
"FROM url, hostname, linking_to, " +
"(SELECT url.id FROM url, hostname " +
"WHERE hostname.name = (?) " +
"AND hostname.id = url.hostname_id " +
") AS siteId " +
"WHERE linking_to.to_id = siteId.id " +
"AND linking_to.from_id = url.id " +
"AND url.hostname_id = hostname.id", t)
result = result.fetchall()
return result
The getIncommingLinks() methond works very well, but getOutgoingLinks() causes an infinite Loop when python trys to execute the SQL statement. Any ideas what went wrong?
Rewrite your Select statements without select ...( Select ...) - thats very bad style. The result may solve your problem.
If by infinite loop you mean that the function doesnt ever get to return a value, I had the same problem.
Found the solution in Why python+sqlite3 is extremely slow?. With large tables it becomes a performance issue with the version shipped with python 2.7. I solved it by upgrading sqlite3 as specified here: https://stackoverflow.com/a/3341117/3894804

Resources