I'm trying to rename one of my selected fields, but it doesn't really work as expected.
This is my code
...
final List<Field<?>> fields = new ArrayList<>();
fields.add(field(name("inner_id"), String.class).as("id"));
fields.add(field(name("inner_name"), String.class).as("name"));
create.select(fields).from(view).where(whereClause, whereBindings);
...
Which translates to:
select "inner_id" "id", "inner_name" "name"
from table
where (inner_id = x)
Instead of
select "inner_id as id", "inner_name as name"
from table
where (inner_id = x)
What am I missing?
Thanks!
The error was actually in the uneccesry quotes.
If anyone else has this error - see this.
Related
Does anybody know is it possible to write in JOOQ select with a set of predefined values? I need it for insert if not exists.
For example,
INSERT INTO test
(text)
SELECT '1234567890123456789'
WHERE
NOT EXISTS (
SELECT id FROM test WHERE text = '1234567890123456789'
);
I've found the answer by myself:
List<Param<?>> params = new LinkedList<>();
params.add(DSL.val("1234567890123456789"));
List<Field<?>> fields = new LinkedList<>();
fields.add(TEST.TEXT);
SelectConditionStep<Record1<TEXT>> notExistsSelect = context.select(TEST.TEXT).from(TEST).where(TEST.TEXT.eq("1234567890123456789"));
SelectConditionStep<Record> insertIntoSelect = context.select(params).whereNotExists(notExistsSelect);
context.insertInto(TEST, fields).select(insertIntoSelect).execute();
But it would be great, if we had an ability to do it via InsertQuery. I've not found the way to do it.
Here is my select statement
SelectQuery<Record> selectQueryPayment = transaction.selectQuery();
selectQueryPayment.addSelect(AccountPayment.ACCOUNT_PAYMENT.PAYMENT_NUMBER,AccountPayment.ACCOUNT_PAYMENT.PAYMENT_AMOUNT,AccountPayment.ACCOUNT_PAYMENT.PAYMENT_TYPE,
AccountPayment.ACCOUNT_PAYMENT.PAYMENT_DATE,AccountPayment.ACCOUNT_PAYMENT.PAYMENT_AMOUNT,AccountPayment.ACCOUNT_PAYMENT.PAYMENT_AMOUNT.subtract(AccountPayment.ACCOUNT_PAYMENT.AMOUNT_REFUNDED.add(AccountPayment.ACCOUNT_PAYMENT.AMOUNT_APPLIED)));
Here you can see a complex select with some calculation
ACCOUNT_PAYMENT.PAYMENT_AMOUNT.subtract(AccountPayment.ACCOUNT_PAYMENT.AMOUNT_REFUNDED.add(AccountPayment.ACCOUNT_PAYMENT.AMOUNT_APPLIED))
How to create Alias for this? And then get back data from it?
Ok I got the solution we can use this
AccountPayment.ACCOUNT_PAYMENT.PAYMENT_AMOUNT.subtract(AccountPayment.ACCOUNT_PAYMENT.AMOUNT_REFUNDED.add(AccountPayment.ACCOUNT_PAYMENT.AMOUNT_APPLIED)).as("OverPayment")
We have to add as("Alias Name") and getting value back we have to use
Result<Record> resultPayment = selectQueryPayment.fetch();
for(Record record : resultPayment){
feeAmount = resultPayment.getValues("OverPayment");
}
I have one table "company" with contains 3 columns [ name,id ,address ]. But I want to fetch only "name " column values. I am doing like this
Dao<Company, String> dao = getDBHelper().getCompanyDao();
QueryBuilder<Company, String> queryBuilder = dao.queryBuilder();
queryBuilder.orderBy(Company.USERNAME_FIELD_NAME, true);
**queryBuilder.selectColumns("name");**
PreparedQuery<Company> preparedQuery = queryBuilder.prepare();
CloseableIterator<Company> iterator = dao.iterator(preparedQuery);
AndroidDatabaseResults results = (AndroidDatabaseResults) iterator.getRawResults();
Cursor cursor = results.getRawCursor();
But application is crashing when I add "queryBuilder.selectColumns("name") ". Please help me.I want cursor since am using cursoradapter to fill data.
crash logs are here :
java.lang.NullPointerException
at com.j256.ormlite.stmt.QueryBuilder.appendFieldColumnName(QueryBuilder.java:593)
at com.j256.ormlite.stmt.QueryBuilder.appendColumns(QueryBuilder.java:585)
at com.j256.ormlite.stmt.QueryBuilder.appendStatementStart(QueryBuilder.java:405)
at com.j256.ormlite.stmt.StatementBuilder.appendStatementString(StatementBuilder.java:122)
at com.j256.ormlite.stmt.StatementBuilder.buildStatementString(StatementBuilder.java:106)
at com.j256.ormlite.stmt.StatementBuilder.prepareStatement(StatementBuilder.java:74)
at com.j256.ormlite.stmt.QueryBuilder.prepare(QueryBuilder.java:98)
But application is crashing when I add "queryBuilder.selectColumns("name")
Wow. This is a very subtle and long standing bug. It will happen whenever you try to select columns from an entity that does not have an ID field. I've added this bug report:
https://sourceforge.net/p/ormlite/bugs/162/
This has been fixed in trunk and will be in 4.49. Here's the check-in.
https://github.com/j256/ormlite-core/commit/ee95883040a3618a1d455b44f6bfd6935a8d4ec7
When trying to update a record for one of my records I am using this code
private void UpdateCattleRecord(UpdateCattleRecord updateRecord){
mDB.beginTransaction();
String where = "_ID=";
String[] RecordToUpdate = {Cattle._ID};
Toast.makeText(this,"Updating Animal "+ RecordToUpdate, Toast.LENGTH_LONG).show();
try {
ContentValues CattleFieldsToUpdate = new ContentValues();
CattleFieldsToUpdate.put(Cattle.CATTLE_ANIMALID,updateRecord.getCattleName());
CattleFieldsToUpdate.put(Cattle.CATTLE_TYPE, updateRecord.getCattleType());
CattleFieldsToUpdate.put(Cattle.CATTLE_LOCATION, updateRecord.getCattleLocation());
CattleFieldsToUpdate.put(Cattle.CATTLE_DOB, updateRecord.getCattleDob());
CattleFieldsToUpdate.put(Cattle.CATTLE_DAM, updateRecord.getCattleDam());
CattleFieldsToUpdate.put(Cattle.CATTLE_SEX, updateRecord.getCattleSex());
mDB.update(Cattle.CATTLE_TABLE_NAME,CattleFieldsToUpdate, where, RecordToUpdate);
mDB.setTransactionSuccessful();
} finally {
mDB.endTransaction();
}
}
My log shows
Tag Database sqlite returned: error code =1, msg = near "=": syntax error
After researching this, I think I have everything in the right place but obviously I don't,
when I look at the next error in the log it's of course in 'red' and it shows me all the correct data,
03-27 15:15:29.291: E/Database(12011): Error updating date_of_birth=March 27, 2012 animaltype=Calf sex=F location=Eastern dam=601 animal_id=601A using UPDATE cattle SET date_of_birth=?, animaltype=?, sex=?, location=?, dam=?, animal_id=? WHERE _ID=
I've obviously got a problem with the value for _ID but can't seem to locate it. Can someone please point out where my Syntax error is?
Update
The problem occurred because I was failing to pass the actual value of the record (_ID) that I wanted to update. Once I passed that as a parameter to my updaterecords function the update went as scheduled.
Thanks for the input, it helped me narrow down what I was doing wrong.
Check your database creation, your probably have a column named _id(although you refer to it by _ID, its name is _id) and not _ID:
String where = "_id= ?"; // ? represent the value from the selection arguments String array
or better:
String where = Cattle._ID + "= ?";
Edit:
In your where selection argument you put:
String[] RecordToUpdate = {Cattle._ID};
you probably want to put in there some id you get from somewhere(of the record you want to update, a long number), right now you're doing:
WHERE _ID = _ID (or _id)
and this will fail.
try:
mDB.update(Cattle.CATTLE_TABLE_NAME,CattleFieldsToUpdate, "_ID="+Cattle._ID, null);
try:
mDB.update(Cattle.CATTLE_TABLE_NAME,CattleFieldsToUpdate, "_ID="+updateRecord.getId(), null);
I installed jOOQ into eclipse, generated classes for my mySQL, but I still have problems to write also some basic queries.
I tried to compose insert query with returning of generated keys, but compiler throws error
Table: tblCategory
Columns: category_id, parent_id, name, rem, uipos
Result<TblcategoryRecord> result= create.insertInto(Tblcategory.TBLCATEGORY,
Tblcategory.PARENT_ID, Tblcategory.NAME, Tblcategory.REM, Tblcategory.UIPOS)
.values(node.getParentid())
.values(node.getName())
.values(node.getRem())
.values(node.getUipos())
.returning(Tblcategory.CATEGORY_ID)
.fetch();
tried also other differnt ways
how to do it right way?
thanks
charis
The syntax you're using is for inserting multiple records. This is going to insert 4 records, each with one field.
.values(node.getParentid())
.values(node.getName())
.values(node.getRem())
.values(node.getUipos())
But you declared 4 fields, so that's not going to work:
create.insertInto(Tblcategory.TBLCATEGORY,
Tblcategory.PARENT_ID, Tblcategory.NAME, Tblcategory.REM, Tblcategory.UIPOS)
What you probably want to do is this:
Result<TblcategoryRecord> result = create
.insertInto(Tblcategory.TBLCATEGORY,
Tblcategory.PARENT_ID, Tblcategory.NAME, Tblcategory.REM, Tblcategory.UIPOS)
.values(node.getParentid(), node.getName(), node.getRem(), node.getUipos())
.returning(Tblcategory.CATEGORY_ID)
.fetch();
Or alternatively:
Result<TblcategoryRecord> result = create
.insertInto(Tblcategory.TBLCATEGORY)
.set(Tblcategory.PARENT_ID, node.getParentid())
.set(Tblcategory.NAME, node.getName())
.set(Tblcategory.REM, node.getRem())
.set(Tblcategory.UIPOS, node.getUipos())
.returning(Tblcategory.CATEGORY_ID)
.fetch();
Probably, you're even better off by using
TblcategoryRecord result =
// [...]
.fetchOne();
For more details, consider the manual:
http://www.jooq.org/doc/2.6/manual/sql-building/sql-statements/insert-statement/
Or the Javadoc for creating INSERT statements that return values:
http://www.jooq.org/javadoc/latest/org/jooq/InsertReturningStep.html
preffered SOLUTION
try {
TblcategoryRecord record = (TblcategoryRecord) create
.insertInto(Tblcategory.TBLCATEGORY)
.set(Tblcategory.PARENT_ID, node.getParentid())
.set(Tblcategory.NAME, node.getName())
.set(Tblcategory.REM, node.getRem())
.set(Tblcategory.UIPOS, node.getUipos())
.returning(Tblcategory.CATEGORY_ID)
.fetchOne();
node.setId(record.getCategoryId());
} catch (SQLException e1) { }
Try
YoutableRecord result = create
.insertInto(YOURTABLE)
.set(YOURTABLE.PROD_NAME, "VAL")
.returning(YOURTABLE.ID_PR)
.fetchOne();
int id = result.getValue(Products.PRODUCTS.ID_PR);