How to Get a Single Result from a SQL Query in Python

How to get a single result from a SQL query in python?

I think you're looking for Cursor.fetchone() :

cursor.fetchone()[0]

Save Looping SQL Query Results as a single table file

That is because of the way you are handling your loop you see friendo. You are creating a new csv file for each looped object. That is why you have multiple CSVs. Why dont you try something like this?

First you create and empty df, object. But with all the definitions like wanted column index, and whatsoevers so you dont get an error

df = pd.DataFrame([],columns = ['col1','col2',...,'coln'])

Then you utilize your loop so concatenate your temporary dfs into your empty df

for row in range(3, sheet.max_row + 1): 
a0, b0, r = sheet.cell(row,1).value, sheet.cell(row,2).value, 0.001
query = """
SELECT a,b,c,d,e FROM smthng
WHERE q3c_radial_query(a,b,{:f},{:f},{:f}) LIMIT 1
""".format(a0,b0,r)
response = qc.query(sql=query,format='csv')
temp_df = convert(response,'pandas')
df = pd.concat([df,temp_df])

After that just use your to_csv method outside of your looparoo.

df.to_csv('your_path')

SQL query only selecting first result

The problem is with your print statement. Right now by giving print result.fetchall()[0][0] you are asking python to print one element. Use

for item in result.fetchall():
print item

retrieving a single value from sql table

The SELECT statement in SQL can be used to query for rows with specific values, and to specify the columns to be returned.

In your case, the code would look something like this


stmt = """\
SELECT Scientific
FROM Names
WHERE Name = ?
LIMIT 1
"""
name = 'Human'
crsr.execute(stmt, (name,))
new_name = crsr.fetchone()[0]

A few points to note:

  • we use a ? in the SELECT statement as a placeholder for the value that we are querying for
  • we set LIMIT 1 in the SELECT statement to ensure that at most only one row is returned, since you want to assign the result to a single variable.
  • the value(s) passed to crsr.execute must be a tuple, even if there is only one value
  • the return value of crsr.fetchone is a tuple, even though we are only fetching one column.

Python: Print only one value of an SQL query result set

You can try to access the data by:

connection = engine.connect()
result = connection.execute("""SELECT DISTINCT Distributor FROM Product""")
result_list = result.fetchall()
result_list[0][0]
connection.close()

Fetch a single record from table using list comprehension in python?

You just can use cursor.fetchone() rather than cursor.fetchall() such as

def fetch_maxno():
dsn_tns = cx_Oracle.makedsn('host', 'port', service_name='serviceno')
connection = cx_Oracle.connect(user='userno', password='pass', dsn=dsn_tns)
cursor = connection.cursor()
sqlquery = "SELECT MAX(attno) AS maxattno FROM hrt"
cursor.execute(sqlquery)
maxno = cursor.fetchone()
connection.close()
return(maxno)

maxno = fetch_maxno()[0]
print(maxno)

How can I take a single column from a SQL query and add it to a list in Python

How are you executing that query? with pyodbc?
then you can actually turn that particular row in to a dictionary

columns = [column[0] for column in cursor.description]
list_of_dict =[]
for dict in cursor.fetchall():
list_of_dict.append(dict(zip(columns, dict)))

print that list_of_dict and you'll understand everything.

Note : you should not execute other queries before performing that code block because cursor will be refreshed.

What I suggest is you is that you access that list and return what you want at the time you are executing that query for some reason.



Related Topics



Leave a reply



Submit