I am new to this, please help me.
I am trying to use ormlite like(column name,value) function, but this is not working for me. But when I test full text it is working like "eq" function.
My Code is,
try {
QueryBuilder<MakeDTO, Integer> qb = makeDao.queryBuilder();
qb.where().like("madeCompany", filterKey);
PreparedQuery<MakeDTO> pq = qb.prepare();
return makeDao.query(pq);
} catch (SQLException e) {
throw new AppException(e);
}
Thanks.
An old question, but something I just solved (ORMLite's documentation isn't that clear). you need to wrap your query parameter in "%"'s in order to tell ORMLite which side of your query string can match any number of characters.
For example, if you want your query to match any madeCompany that contains your string use the following:
try {
QueryBuilder<MakeDTO, Integer> qb = makeDao.queryBuilder();
qb.where().like("madeCompany", "%"+filterKey+"%");
PreparedQuery<MakeDTO> pq = qb.prepare();
return makeDao.query(pq);
} catch (SQLException e) {
throw new AppException(e);
}
Pretty simple, you're asking it to be exactly the string 'madeCompany', if you want to do partial matching you need to use the % wildcard etc.
public Where<T,ID> like(java.lang.String columnName,
java.lang.Object value)
throws java.sql.SQLException
Add a LIKE clause so the column must mach the value using '%' patterns.
Throws:
java.sql.SQLException
Where.like(java.lang.String, java.lang.Object)
The answers above can resolved the like query problem, but has SQL injection risk. If the value of 'filterKey' is ', it will cause SQLException, because the SQL will be SELECT * FROM XXX WHERE xxx LIKE '%'%'. You could use SelectArg to avoid, example for this case:
try {
String keyword = "%"+filterKey+"%";
SelectArg selectArg = new SelectArg();
QueryBuilder<MakeDTO, Integer> qb = makeDao.queryBuilder();
qb.where().like("madeCompany", selectArg);
PreparedQuery<MakeDTO> pq = qb.prepare();
selectArg.setValue(keyword);
return makeDao.query(pq);
} catch (SQLException e) {
throw new AppException(e);
}
Reference: http://ormlite.com/javadoc/ormlite-core/doc-files/ormlite_3.html#index-select-arguments
Related
I want to pass a few dates to this method, and get a few objects from the DB in return.
QueryBuilder<WorkDayDB, Long> queryBuilder =
application.ormLiteDatabaseHelper.getWorkDayDBDao().queryBuilder();
Where where = queryBuilder.where();
try {
where.eq("date", dates);
return queryBuilder.prepare();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
However, the where.eq("date", dates); throws an exception, saying it needs a single Date, not an array of dates.
Apparently eq means equals which is specifically used for a single argument, whereas in (which is another method of where in OrmLite) allows for an array of arguments to be passed. This solved my problem.
I'm looking at the tutorial for Spatialite-Android, and I'm noticing the following code samples:
String query = "SELECT AsText(Transform(MakePoint(" + TEST_LON + ", " + TEST_LAT + ", 4326), 32632));";
sb.append("Execute query: ").append(query).append("\n");
try {
Stmt stmt = db.prepare(query);
if (stmt.step()) {
String pointStr = stmt.column_string(0);
sb.append("\t").append(TEST_LON + "/" + TEST_LAT + "/EPSG:4326").append(" = ")//
.append(pointStr + "/EPSG:32632").append("...\n");
}
stmt.close();
} catch (Exception e) {
e.printStackTrace();
sb.append(ERROR).append(e.getLocalizedMessage()).append("\n");
}
In particular, I noticed that poor practice is done of simply stringing together a SQL query, instead of a more proper method, such as is used by the Android SQLite library. Is there a way that I can make Spatialite use true prepared statements?
Just to be clear, I'm looking for something like this, using the standard SQLite database in Android:
String query="SELECT * FROM table WHERE _id=?";
Cursor data=db.rawQuery(query,new String[]{id});
There are a few tricks. They all use the exec() call, which has 3 arguments for this version. The statement from the source code is:
public void exec(String sql, jsqlite.Callback cb, String args[])
A jsqlite.Callback is an interface, of which there can be several. But the best way seems to be using a db.get_table(query,args) function. %q is the effective replacement for ? in the Android SQLite representation. Here's the transformation of the given code:
String query = "SELECT AsText(Transform(MakePoint(%q, %q, 4326), 32632));";
TableResult result=db.get_table(query,new String[]{""+TEST_LONG,""+TEST_LAT});
From there, you just have to get the results from TableResult. There isn't a method call to get the results from here, you actually have to grab the publicly declared variable and manually parse through it. Here's an example of how that can be done.
TableResult result=db.get_table(query,new String[]{""+lng,""+lat});
Vector<String[]> rows=result.rows;
for (String[] row:rows)
{
for (String val:row)
{
Log.v(TAG,val);
}
}
If you aren't doing a select, try something like this:
TableResult result=new TableResult();
db.exec("ATTACH DATABASE %q AS newDb",result,new String[]{path});
I assume the same pattern will work for INSERTS and the like
i am using ormlite version 4.46 I am able to get the desired result when i run a raw query but somehow the result is null when i am trying it in ormlite can someone please explain where i am making a mistake.
Snippet:
String query=
"SELECT Products.* FROM "+DBConst.TABLE_PRODUCTS
+" INNER JOIN "+DBConst.TABLE_OFFERS_MAPPING
+" ON Products."+DBConst.PROD_ID+" = OffersMapping."+DBConst.OFFERS_PRODUCT_ID
+" WHERE "+DBConst.OFFERS_OFFER_ID+ " = "+offerId+
" GROUP BY "+DBConst.PROD_PARENT_PRODVAR_ID;
GenericRawResults<Product> rawResults = productDao.queryRaw(query, productDao.getRawRowMapper());
//produces this query:SELECT Products.* FROM Products INNER JOIN OffersMapping ON Products._id = OffersMapping.product_id WHERE offer_id = 141 GROUP BY variant_id
List<Product> prodList = rawResults.getResults();
rawResults.close();
Gives me desired result....
Now to ormlite
Dao<Product, String> productDao = helper.getProductDao();
Dao<OfferMapping, String> offerMappingDao = helper.getOfferMappingDao();
try {
QueryBuilder<Product, String> productQb = productDao.queryBuilder();
QueryBuilder<OfferMapping, String> offerQb = offerMappingDao.queryBuilder();
//to sort the offer id accordingly
offerQb.where().eq(DBConst.OFFERS_OFFER_ID, offerId);
productQb.where().eq(DBConst.PROD_ID, new ColumnArg(DBConst.OFFERS_PRODUCT_ID));
productQb.join(offerQb);
productQb.groupBy(DBConst.PROD_PARENT_PRODVAR_ID);
Constants.showLog("Query", "Query is "+productQb.query());//gets null here
List<Product> prodList = productQb.query();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
Dont know where i am making a mistake...
i am using ormlite version 4.46 I am able to get the desired result when i run a raw query but somehow the result is null when i am trying it in ormlite can someone please explain where i am making a mistake.
Sorry for the late response. I would log the generated query from the ORMLite query-builder and then compare it with your hand generated query. You can log the results of productQb.prepareStatementString() before the query is performed. For more information see the logging documentation.
Let me know if ORMLite is doing something wrong.
I have a problem with making request using these both libraries. I wanted to get all queries from my table Table_events with .queryforall() but then I saw this thread and tried to make query with rawQuery but it offers only queryRaw(). The request looks like this:
private Dao<Table_Events, Integer> tEventDao;
public DAOManager(final DatabaseHelper databaseHelper)
{
this.tEventDao= GettEventDAO(databaseHelper);
}
public String[] Getall()
{
GenericRawResults<String[]> rawResults = null;
try
{
rawResults = tEventDao.queryRaw("select * from tableEvents");
}
catch (SQLException e)
{
e.printStackTrace();
}
return resultArray;
}
any ideas how make a query?
Your GettEventDAO function is returning an object that conforms to the Dao interface of ORMLite. You would need to make sure the implementation of ORMLite is able to interface with SQLCipher for Android which would typically return a Cursor representing the resultset of your query.
I have two tables CustomerBalance and Customer which are bound with CustomerRefId field.
I want the CustomerBalance records that are lets say greater than 100 for a field balance of this tables. I also want to include into my results the name of the particular customer that fulfills that criteria. I created the following method that works!
public List<CustomerBalance> getCustomerBalanceFilter(String filterVal) {
try {
PreparedQuery<CustomerBalance> preparedQuery = mDbHelper.getCustomerBalanceDao().queryBuilder()
.where().gt(CustomerBalance.DB_COL_CUSTOMER_BALANCE, filterVal)
.prepare();
List<CustomerBalance> result = mDbHelper.getCustomerBalanceDao().query(preparedQuery);
for(CustomerBalance alert : result) {
PreparedQuery<Customer> getCustQuery = mDbHelper.getCustomerDao().queryBuilder()
.where().eq(Customer.DB_COL_CUSTOMER_REF_ID, alert.getCustomerID())
.prepare();
List<Customer> customer = mDbHelper.getCustomerDao().query(getCustQuery);
alert.setCustomer(customer.size() == 1 ? customer.get(0) : null);
}
return result;
} catch(Exception ex) {
return null;
}
}
This methods is working, is this the best way to write such a query? or is there a more appropriate approach?
One improvement to your query is to use ORMLite's SelectArg to pass in the customer-id instead of a new query each time. Something like:
...
List<CustomerBalance> result = mDbHelper.getCustomerBalanceDao()
.query(preparedQuery);
SelectArg custIdArg = new SelectArg();
PreparedQuery<Customer> getCustQuery = mDbHelper.getCustomerDao().queryBuilder()
.where().eq(Customer.DB_COL_CUSTOMER_REF_ID, custIdArg)
.prepare();
for (CustomerBalance alert : result) {
custIdArg.setValue(alert.getCustomerID());
List<Customer> customer = mDbHelper.getCustomerDao().query(getCustQuery);
alert.setCustomer(customer.size() == 1 ? customer.get(0) : null);
}
Here are the docs for SelectArg:
http://ormlite.com/docs/select-arg
FYI, there also is an UpdateBuilder, but I don't see an easy way to turn your code above into a single UPDATE statement.