Updating value in table sqlalchemy postgres [duplicate] - python

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

Related

How to only get second row data from Sqlite? [duplicate]

This question already has answers here:
Sqlite LIMIT / OFFSET query
(3 answers)
Closed 12 months ago.
I am new to Python and I recently stuck in getting value from Sqlite. What I want is getting value only in second row of the table. This is the table data picture. And I have tried this but not working:
con = sqlite3.connect(database=r'ims.db')
cur = con.cursor()
for l in range(1,8):
cur.execute(f"Select occolor{l} from ordercart limit 2")
row = cur.fetchall()
print(row)
This will bring both first and second row value. But what I want are only the second row value. Anyone help with this pls?
fetchall returns a reference to a list. Your query will return at most 2 rows. Therefore:
if (row := cur.fetchall()):
print(row[-1])
else:
print('Not found')
Doing it like this allows for the results being either empty or containing just one row

SQLAlchemy Multiple Where Condition [duplicate]

This question already has answers here:
sqlalchemy filter multiple columns
(4 answers)
Closed last year.
I have an Orders table. And I want to write a query to this table with more than one condition. For example, I want to get an order with id field 1 and order_status field 3.
Is there a way to do this with SQL Alchemy?
P.S. I am able to check only one condition with the following query.
order = Orders.query.filter_by(restaurant_id = restaurant_id).all()
There are multiple ways of doing this for example if you want to apply an and operation you can simply use filter chain as below
order = Orders.query.filter(restaurant_id = restaurant_id).filter(id = 1).filter(order_status = "Status").all()
You can also use and_ and or_ to apply respective conditions like below.
cond = and_(restaurant_id = restaurant_id, id = 1)
order = Orders.query.filter(or_(cond, order_status = "Status")).all()

take one value out of fetchone sqlalchemy query result [duplicate]

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.

Iterate over databse array flask [duplicate]

This question already has answers here:
Iterating over dictionaries using 'for' loops
(15 answers)
Closed 2 years ago.
I am relatively new to flask and I am having some issues with displaying my database as a html table. I don't know if this might be a stupid question, but I don't know how to get the values from this array.
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT CardNo, CardName, CardExpDate, CardSecretCode FROM carddetails WHERE UID=%s", (session['id'],))
rows = cursor.fetchall()# data from database
for row in rows:
print(row)
for i in row:
print(i)
{'CardNo': '4561441635108144', 'CardName': 'Zachery Williamson', 'CardExpDate': '12-25', 'CardSecretCode': '219'}
CardNo
CardName
CardExpDate
CardSecretCode
{'CardNo': '4590618204792680', 'CardName': 'SAM LETTUCE', 'CardExpDate': '03-23', 'CardSecretCode': '440'}
CardNo
CardName
CardExpDate
CardSecretCode
I want to get the values next to the colon for each of them, but I don't know why it only returns the first bit which is useless for my purpose. My idea is implementing those values in a html table, but I am struggling with it. By the way, tha card information displayed above is completely random.
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT CardNo, CardName, CardExpDate, CardSecretCode FROM carddetails WHERE UID=%s", (session['id'],))
rows = cursor.fetchall()# data from database
for row in rows:
print(row)
for i in row:
print(i, row[i])
With for i in row, you iterate over a dictionary and i is a key for each iteration. To get the associated value, you have to get it like for all dictionaries in Python row[i].

sqlite3: How to use SELECT + WHERE to search a random row? [duplicate]

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

Categories

Resources