On my example below, I am using sqlalchemy orm to update the values of a column (column_2) conditional to the values of another column (column_1).
I am currently using two updates to achieve that.
Is it possible to combine these two updates into one? That would save the second execute on my code below.
update_1 = update(table).where(table.c[column_1] != "ABC").values({table.c[column_2]:(table.c[column_3] * table.c[column_4]) })
db.execute(update_1)
update_2 = update(table).where(table.c[column_1] == "ABC").values({table.c[column_2]:table.c[column_3] })
db.execute(update_2)
This question already has answers here:
How to use variables in SQL statement in Python?
(5 answers)
Closed 8 months ago.
I am trying to update a value in my table, and add it back in into the database. However, it does not seem to be updating the table when I do db.session.commit.
Example of Category table:
Category(id=1, catInfo="{}", products = "[{}]")
Here are my steps:
products2 = json.dumps([{'info': 'info'}])
# I am trying to update products in Category with an ID of 1 with a new list
db.engine.execute("UPDATE products FROM Category WHERE id = 1" + " SET products = " + products2)
# commit the database
db.session.commit()
I am getting TypeError: dict is not a sequence No idea why
As Chris commented, you need to write a query to insert the data back in the database. Here is an example on how to insert an object in sqlalchemy:
customer = Customer(
first_name='Todd',
last_name='Birchard',
email='fake#example.com',
preferred_language='English',
join_date=datetime.now()
)
session.add(customer)
session.commit()
If you need to add multiple objects, consider add_all instead. Reference
This question already has answers here:
Getting COUNT from sqlalchemy
(3 answers)
Closed 2 years ago.
from a lambda function in AWS I am calling a stored procedure in Snowflake. I run python code and use sqlalchemy and snowflake.sqlalchemy modules to call the snowflake stored proc. the stored procedure queries a table with one row and one column, does a simple calculation and returns a single value. The code looks like this:
result=connection.execute('CALL TEST_GET_PARAMS(8,8);')
sql='select * from CALCRESULT;'
rows = result.fetchone()
print(rows)
print (type(rows))
the return looks like this:
(160.0,)
<class 'sqlalchemy.engine.result.RowProxy'>
However, I want to value to be an int value without the ( ) and ,
I am assuming my problem is in the use of fetchone and then how take the first column out of the result, but I don't know how to do it.
Any suggestions?
The RowProxy object returned by result.fetchone() permits dictionary-style access of columns within.
For example, if the lone column inside your CALCRESULT table is called COLUMN_NAME then you can use this to retrieve just its value:
>>> […]
>>> row = result.fetchone()
>>> value = row["COLUMN_NAME"]
>>> print(value)
160.0
You can try using fetchmany(size=1) inplace of fetchone().And define the size limit according to your column requirement.
This question already has answers here:
SQLite - ORDER BY RAND()
(5 answers)
Closed 5 years ago.
Eg. In the Table1 there is a column ColName, some of the items in ColName are "Mike".
The code to search one of the them:
searchString = " SELECT * FROM Table1 WHERE ColName = 'Mike' "
cur.execute(searchString).fetchone()
The Problem: The code above allways gives me the first row, where "Mike" in ColName appears.
I actually want, by everytime running the sqlite code, to get a random search result from the column ColName, whose value is "Mike". How could I change the code?
Thanks for the help!
If you want a random value, then you need to iterate over cur.execute(searchString) for some random amount, then extract the column(s).
fetchone() always returns the top result
The alternative includes trying to randomly sort the query results in SQL
Is it possible to do SELECT * in SQLAlchemy?
Specifically, SELECT * WHERE foo=1?
Is no one feeling the ORM love of SQLAlchemy today? The presented answers correctly describe the lower-level interface that SQLAlchemy provides. Just for completeness, this is the more-likely (for me) real-world situation where you have a session instance and a User class that is ORM mapped to the users table.
for user in session.query(User).filter_by(name='jack'):
print(user)
# ...
And this does an explicit select on all columns.
The following selection works for me in the core expression language (returning a RowProxy object):
foo_col = sqlalchemy.sql.column('foo')
s = sqlalchemy.sql.select(['*']).where(foo_col == 1)
If you don't list any columns, you get all of them.
query = users.select()
query = query.where(users.c.name=='jack')
result = conn.execute(query)
for row in result:
print row
Should work.
You can always use a raw SQL too:
str_sql = sql.text("YOUR STRING SQL")
#if you have some args:
args = {
'myarg1': yourarg1
'myarg2': yourarg2}
#then call the execute method from your connection
results = conn.execute(str_sql,args).fetchall()
Where Bar is the class mapped to your table and session is your sa session:
bars = session.query(Bar).filter(Bar.foo == 1)
Turns out you can do:
sa.select('*', ...)
I had the same issue, I was trying to get all columns from a table as a list instead of getting ORM objects back. So that I can convert that list to pandas dataframe and display.
What works is to use .c on a subquery or cte as follows:
U = select(User).cte('U')
stmt = select(*U.c)
rows = session.execute(stmt)
Then you get a list of tuples with each column.
Another option is to use __table__.columns in the same way:
stmt = select(*User.__table__.columns)
rows = session.execute(stmt)
In case you want to convert the results to dataframe here is the one liner:
pd.DataFrame.from_records(rows, columns=rows.keys())
For joins if columns are not defined manually, only columns of target table are returned. To get all columns for joins(User table joined with Group Table:
sql = User.select(from_obj(Group, User.c.group_id == Group.c.id))
# Add all coumns of Group table to select
sql = sql.column(Group)
session.connection().execute(sql)
I had the same issue, I was trying to get all columns from a table as a list instead of getting ORM objects back. So that I can convert that list to pandas dataframe and display.
What works is to use .c on a subquery or cte as follows:
U = select(User).cte('U')
stmt = select(*U.c)
rows = session.execute(stmt)
Then you get a list of tuples with each column.
Another option is to use __table__.columns in the same way:
stmt = select(*User.__table__.columns)
rows = session.execute(stmt)
In case you want to convert the results to dataframe here is the one liner:
pd.DataFrame.from_records(dict(zip(r.keys(), r)) for r in rows)
If you're using the ORM, you can build a query using the normal ORM constructs and then execute it directly to get raw column values:
query = session.query(User).filter_by(name='jack')
for cols in session.connection().execute(query):
print cols
every_column = User.__table__.columns
records = session.query(*every_column).filter(User.foo==1).all()
When a ORM class is passed to the query function, e.g. query(User), the result will be composed of ORM instances. In the majority of cases, this is what the dev wants and will be easiest to deal with--demonstrated by the popularity of the answer above that corresponds to this approach.
In some cases, devs may instead want an iterable sequence of values. In these cases, one can pass the list of desired column objects to query(). This answer shows how to pass the entire list of columns without hardcoding them, while still working with SQLAlchemy at the ORM layer.