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

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

Related

Updating value in table sqlalchemy postgres [duplicate]

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

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].

If statement in Flask using string variable from SQL database

I'm creating a program where I need to check if a certain cell in a table equals a string value and, if it does not, to not change that value. Here is some snippet of the code for clarification:
if (db.execute("SELECT :rowchosen FROM userboard WHERE column=:columnchosen", rowchosen = rowchosen, columnchosen = columnchosen)) == '-'):
#change value of cell
else:
#go to a new page that displays an error
Yet, whenever I run this code, I always get an error because the value (I believe) prints as a dictionary value, something like {"row" = 'row'} of that sort. Any help/advice as to why this happens?
Are you sure that userboard is the database and not the table?
i think, here is what you want to do
conn = sqlite3.connect(db_file)
cur = conn.cursor()
cur.execute("SELECT * FROM userboard WHERE one=?", (columnchosen,))
rows = cur.fetchall()
for row in rows:
print(row)
now, in the loop for row in rows: you need to perform your check. For all the rows returned, you need to check each row for - in the appropriate column
also check out http://www.sqlitetutorial.net/sqlite-python/sqlite-python-select/

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

How to select second parameter from fetchall() in pyodbc

I am new in python so in the pyodbc. Maybe my question is very simple but I could not find any answer refer to my question.
I'm using this select
cursor.execute("SELECT [something] FROM [someone] WHERE [user_name]='John'")
rows = cursor.fetchall()
for row in rows:
print row.something
It prints some parameters for example 4 or 5.How to print only second or only third parameter.
I also used cursor.fetchmany() but I'm having same problem
If you wan't just the 4th row you can do:
rows = cursor.fetchall()
print rows[3].something
But it's better if you do it in the SQL query and avoid fetching all the rows from the database:
SELECT [something] FROM [someone] WHERE [user_name]='John' LIMIT 1 OFFSET 3
Example.
I guess your mean field and not parameter
cursor.execute("SELECT [something] FROM [someone] WHERE [user_name]='John'")
rows = cursor.fetchall()
from row in rows:
print row[1]

Categories

Resources