Update Record in SQL for a specific row - sqlalchemy

I am trying to update a record using sqlalchemy.
tableA.query().\
filter(tableA.id== 9080).\
update({"bankbalance": (tableA.bankbalance+1)})
tableA.commit()
In tableA, there are two columns - id and bankbalance.
I want to update the bankbalance for the person with id 9080.
But the query is not working because I am getting the error below.
TypeError: 'BaseQuery' object is not callable

Use db.session.query(), if you don't query a model.
db.session.query(tableA).filter(tableA.id == 9080).\
update({"bankbalance": (tableA.bankbalance+1)})
db.session.commit()

Related

How to print query of Django ORM

I am using Django ORM query with Extra params. when I try to print the SQL query relevant to that ORM Query,i am getting the below Error message.
ORM Query:
Record = SAMPLE_TABLE.objects.extra(where=["REPLACE(Message,' ','') "+whereCaseSensitive+" like %s "+query],params=[duplicateCheckMessage]).filter(~Q(iStatus=2),~Q(iAppStatus=2),iEntityID=entityId,iTemplateType=1).first()
Message - FieldName ,
whereCaseSensitive - '',
query - ( FIND_IN_SET("test",Testfield))
I am trying to fetch the sql query related to this using
print(Record.query)
when i run this i am getting Exception as 'NoneType' object has no attribute 'query'
Can any one help on this ?
You can't print the query for the first (or any) element of a queryset because it is an instance, not a query. To print .query you need to do it on the queryset
Try this
my_query = SAMPLE_TABLE.objects.extra(*some_extra).filter(*some_filter)
print(my_query.query)
record = my_query.first()

How to access columns after doing outerjoin in sqlalchemy

I did outerjoin of two tables. And I got the correct result. But I don't know how to access the Columns in the result. Below is my code.
result = db.session.query(Purchase, Product.pr_id).outerjoin(Product, Purchase.id == Product.pr_id).filter(Purchase.user_id==current_user.id, Product.status==pr_status).order_by(desc(Purchase.cost)).all()
'result[0].Purchase.cost' gives me cost of the first purchase. But 'result[0].Product.status' giving AttributeError: Could not locate column in row for column 'Product'.
Why this happen ? How can I access the 'status' column
Changing the second argument of db.session.query() from Product.pr_id to Product should work.
result = db.session.query(Purchase, Product).outerjoin(Product, Purchase.id == Product.pr_id).filter(Purchase.user_id==current_user.id, Product.status==pr_status).order_by(desc(Purchase.cost)).all()
This is in the docs at selecting-orm-entities-and-attributes] in the example with
stmt = select(User, Address).join(User.addresses).order_by(User.id, Address.id)

Not retrieving set of values from table. Laravel

I'm trying to get values from my linking table sfees with columns student_id and mfee_id. Here, there might be multiple student_id with different mfee_id. The thing is that, i want to retrieve all mfee_id with same student_id.
I have used following syntax, but it is only returning single value:
public function verify($id,$sid)
{
$sfees = sfee::where('student_id', $sid)->value('mfee_id');//trying to get only mfee_id
return $sfees;
}
How can i solve this problem?
//edited
My table looks like:
You need to do a groupBy -
$sfees = sfee::where('student_id', '=',$sid)->groupBy('student_id')->get();
UPDATE
Try something like this -
$sfees = sfee::where('student_id', '=',$sid)->lists('mfee_id');
Or you can use the Schema Builder like this -
DB::table('sfees')->where('student_id', '=', $id)->lists('mfee_id');

Matlab Database QueryDb error

I need to insert some data into a mysql database. Db is connected and working.
I am running the following code :
a = sprintf('%s',hashedStr);
sqlQueryStr = 'insert into products (security_code) values (a)'
QueryDB(sqlQueryStr);
I have a database called test and a table named products with 2 fields id and security_code.
When I run this, I get :
Unknown column 'a' in fieldlist ...
Why is this happening ? i dont have and dont need this column ...
Any help ?
Try with:
sqlQueryStr = sprintf('insert into products (security_code) values ("%s")',hashedStr);
QueryDB(sqlQueryStr);
problem is that you are not replacing "a" variable into sql expression

JPA passing parameter as Set

i want to pass a parameter in the jpql as set in an update statement. here is the statement:
Query query = entityManager.createQuery("UPDATE Patient patient SET "
+"patient.surname=:surname, "
+"patient.firstname=:firstname, "
+"patient.homeAddress=:homeAddress, "
+"patient.relatedPersons=:relatedPersons, "
+"patient.hospital=:hospital "
+"WHERE patient.id=:id");
query.setParameter("surname", updatablePatient.getSurname());
query.setParameter("firstname", updatablePatient.getFirstname());
query.setParameter("homeAddress", updatablePatient.getHomeAddress());
query.setParameter("relatedPersons", updatablePatient.getRelatedPersons());
query.setParameter("hospital", updatablePatient.getHospital());
query.setParameter("id", id);
but i get the following error:
org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [****] was not matching type [java.util.Set]; nested exception is java.lang.IllegalArgumentException: Parameter value [****] was not matching type [java.util.Set]
any help would be really appreciated.
thanks in advance
Update statements in JPQL are rarely used, and should be used for batch updates, but not simply to update one entity. They translate directly to SQL, and you can't update a patient and all his related persons like this in SQL. The same goes for JPQL.
To do what you want to do, just get the patient from the database, and set the new properties into the loaded patient :
Patient p = (Patient) entityManager.find(Patient.class, id);
p.setSurname(updatablePatient.getSurname());
p.setRelatedPersons(updatablePatient.getRelatedPersons());
// ... set other properties
Or, if the updatable patient is a detached copy of the patient to update, and thus has the same ID,
Patient p = (Patient) entityManager.merge(updatablePatient);
The whole point of JPA (or at least one of its points) is to be able to use and modify an object graph rather than use queries to create and update data in database.
There is no support for updating set (or in general any collection valued field) via JPQL. In JPA 2.0 specification this is spelled as follows:
update_clause ::= UPDATE entity_name [[AS] identification_variable]
SET update_item {, update_item}*
update_item ::= [identification_variable.]
{state_field | single_valued_object_field} = new_value
For more details: JPQL BNF