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

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

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

In a Python data frame, how do you extract a specific element in one column after finding the row that element belongs to? [duplicate]

This question already has answers here:
How do I select rows from a DataFrame based on column values?
(16 answers)
Closed 1 year ago.
What I'm trying to do is create a function that returns the frequency or count of a name input into the function. For example, if I inputted 'Olivia' into my get_frequency(name) function I would want 19674 returned.
You don't actually need this if condition, you could just search for the 'Count' value when df['name'] is equal to the name you are searching for.
snippet of code:
def get_frequency(name):
return df['Count'][df['Name']==name]
if you want the scalar value you could use values like this:
def get_frequency(name):
return df['Count'][df['Name']==name].values[0]
as a result you'd get:
get_frequency('Emma')
>> 20799
In your sintax above:
df.loc[df.Name == 'name', 'Count]
or you can use at
df.at[row_index, col_index]
will return the scalar of the position, or you can use the index number:
df.iat[row_pos_number, col_pos_number]

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

sqlite - return all columns for max of one column without repeats

Im using Python to query a SQL database. I'm fairly new with databases. I've tried looking up this question, but I can't find a similar enough question to get the right answer.
I have a table with multiple columns/rows. I want to find the MAX of a single column, I want ALL columns returned (the entire ROW), and I want only one instance of the MAX. Right now I'm getting ten ROWS returned, because the MAX is repeated ten times. I only want one ROW returned.
The query strings I've tried so far:
sql = 'select max(f) from cbar'
# this returns one ROW, but only a single COLUMN (a single value)
sql = 'select * from cbar where f = (select max(f) from cbar)'
# this returns all COLUMNS, but it also returns multiple ROWS
I've tried a bunch more, but they returned nothing. They weren't right somehow. That's the problem, I'm too new to find the middle ground between my two working query statements.
In SQLite 3.7.11 or later, you can just retrieve all columns together with the maximum value:
SELECT *, max(f) FROM cbar;
But your Python might be too old. In the general case, you can sort the table by that column, and then just read the first row:
SELECT * FROM cbar ORDER BY f DESC LIMIT 1;

Categories

Resources