Python SQLite3 fetch raw? - python

I have a problem with this code :
cur.execute('SELECT Balance FROM accounts')
print(cur.fetchone())
That outputs: (0,) instead of what I want 0.
Can anyone help to fix the error? Any help is very much appreciated!

fetchone() would return you a single table row which may contain multiple columns. In your case it is a single column value returned in a tuple. Just get it by index:
data = cur.fetchone()
print(data[0])

It's possible there would be more than one value in your query, so it always returns a tuple (you wouldn't want an interface which changes depending upon the data you pass it would you?).
You can unpack the tuple:
value, = cur.fetchone()
See the last paragraph of the documentation on tuples and sequences for information about sequence unpacking

Related

python cursor return only those rows which first column is not empty

In Python 3.8, I have a select query.
dbconn.execute("select name, id, date from test_table")
That query returned always wrong number of rows. After too much debugging, I was able to fix it by only replacing id column place with name column and it started working normally.
The issue was with empty value for name column for some rows.
It means, python cursor returns only those rows which first column is not empty. Do I miss anything in my conclusion?
Check your database integrity, it might be that some of the entries are corrupted thus failing. Cuz I had issue before that the query is failing (wrong number of output) at some point due to integrity issue.
1 thing also is instead of returning the row as list/tuple, try it with dictionary-like with key-value pair.
dbconn.row_factory = sqlite3.Row

TypeError: tuple indices must be integers, not str

I am trying to pull data from a database and assign them to different lists.
This specific error is giving me a lot of trouble "TypeError: tuple indices must be integers, not str"
I tried converting it to float and etc, but to no success.
The code goes as below
conn=MySQLdb.connect(*details*)
cursor=conn.cursor()
ocs={}
oltv={}
query="select pool_number, average_credit_score as waocs, average_original_ltv as waoltv from *tablename* where as_of_date= *date*"
cursor.execute(query)
result=cursor.fetchall()
for row in result:
print row
ocs[row["pool_number"]]=int(row["waocs"])
oltv[row["pool_number"]]=int(row["waoltv"])
Sample output of print statement is as follows :
('MA3146', 711L, 81L)
('MA3147', 679L, 83L)
('MA3148', 668L, 86L)
And this is the exact error I am getting:
ocs[row["pool_number"]]=int(row["waocs"])
TypeError: tuple indices must be integers, not str
Any help would be appreciated! Thanks people!
Like the error says, row is a tuple, so you can't do row["pool_number"]. You need to use the index: row[0].
I think you should do
for index, row in result:
If you wanna access by name.
TL;DR: add the parameter cursorclass=MySQLdb.cursors.DictCursor at the end of your MySQLdb.connect.
I had a working code and the DB moved, I had to change the host/user/pass. After this change, my code stopped working and I started getting this error. Upon closer inspection, I copy-pasted the connection string on a place that had an extra directive. The old code read like:
conn = MySQLdb.connect(host="oldhost",
user="olduser",
passwd="oldpass",
db="olddb",
cursorclass=MySQLdb.cursors.DictCursor)
Which was replaced by:
conn = MySQLdb.connect(host="newhost",
user="newuser",
passwd="newpass",
db="newdb")
The parameter cursorclass=MySQLdb.cursors.DictCursor at the end was making python allow me to access the rows using the column names as index. But the poor copy-paste eliminated that, yielding the error.
So, as an alternative to the solutions already presented, you can also add this parameter and access the rows in the way you originally wanted. ^_^ I hope this helps others.
I know it is not specific to this question, but for anyone coming in from a Google search: this error is also caused by a comma behind an object that creates a tuple rather than a dictionary
>>>dict = {}
>>>tuple = {},
Tuple
>>>tuple_ = {'key' : 'value'},
>>>type(tuple_)
<class 'tuple'>
Dictionary
>>>dict_ = {'key' : 'value'}
>>>type(dict_)
<class 'dict'>
Just adding a parameter like the below worked for me.
cursor=conn.cursor(dictionary=True)
I hope this would be helpful either.
The Problem is how you access row
Specifically row["waocs"] and row["pool_number"] of ocs[row["pool_number"]]=int(row["waocs"])
If you look up the official-documentation of fetchall() you find.
The method fetches all (or all remaining) rows of a query result set and returns a list of tuples.
Therefore you have to access the values of rows with row[__integer__] like row[0]
SQlite3 has a method named row_factory. This method would allow you to access the values by column name.
https://www.kite.com/python/examples/3884/sqlite3-use-a-row-factory-to-access-values-by-column-name
I see that you're trying to identify by the name of a row. If you are looking for a specific column within the row, you can do [integer][column name]
For example, to iterate through each row and only pull out the value from the row with the column header of "pool number", you can do this:
for row in df_updated.iterrows():
cell = row[1]['pool number']
print(cell)
The code will then iterate through each row but only print out the value that matches the "pool number" column

Why does fetchone()[0] return a 'Nonetype'

I'm trying to store the employeeid value from employee table, to get the specific row I use the following command on Python:
cursor.execute("SELECT*FROM EMPLOYEE WHERE first_name = %s AND last_name = %s", (employee['firstname'],employee['lastname']))
followed by
employeeid=cursor.fetchone()[0]
why does employeeid have value Nonetype?
The reason fetchone()[0] returns None is almost certainly that the first column in the first row matching your WHERE clause has a NULL value.
Since you're just doing SELECT * rather than providing a column list, the first column could be any of the columns in the table. If you specifically want the employeeid column, you should SELECT employeeid.
Also, since you're not using ORDER BY, the first row could be any of the matching rows. So make sure there aren't multiple rows matching your WHERE clause (unless you expect there to be). It's possible that you have one "good" row with a value of 23, plus another "bad" row with a value of NULL.
As StefanPochmann points out, it's also possible that you didn't find any rows, and you've misinterpreted the results. If a query returns nothing, the fetchone() call will either return None, or raise an exception. In this first case, your statement would cause an error like TypeError: 'NoneType' object is not subscriptable, because cursor.fetchone()[0] is effectively doing None[0]. In the second case, the exception from fetchone itself might mention NoneType somewhere. In neither case is employeeid ending up with the value NoneType as you claim, but if you're not looking in the right place, you might have somehow convinced yourself that it is.
Answered here, click me
7
When you call execute, the results are computed and fetched, and you use fetchone/fetchmany/fetchall to retrieve them.
In your case, your query returns a single row as the result, so calling cursor.fetchone in the if causes the result to be fetched and subsequently thrown away, so another call to fetchone will yield None as the pointer has already advanced past the only row in the result set.
The idiomatic sqlite way of checking if data exists, is to query a row, and test its truthiness -
While you could be looking at a null valued column in a valid row, I strongly suspect that you did not match any rows. You can check if you matched a row by printing the results of your cursor.fetchone(). I think you did not match any rows because of the way you sent your parameters to sql. inserting them into the string, you need to quote the string parameters like:
cursor.execute("SELECT*FROM EMPLOYEE WHERE first_name = '%s' AND last_name = '%s'", (employee['firstname'],employee['lastname']))
the preferred option is pass them in as sql parameters like:
stmt = "SELECT * FROM EMPLOYEE WHERE first_name = ? AND last_name = ?"
result = cursor.execute (stmt,(employee['firstname'],employee['lastname']))

python oracle SQL query conversion

I'm trying to get a certain value from an oracle database and print a string with the value of the oracle database query.
con=cx_Oracle.connect('username/pword')
cur=con.cursor()
fList=()
obj=cur.execute('''select sequence from genes where key=54321''')
cur.close()
con.close()
print str(obj)
I get this output:
<cx_Oracle.Cursor on <cx_Oracle.Connection to user hendrik#local>>
But I'd like to get the value of sequence for this unique key/row.
What you are seeing there is a Cursor object. It in itself is iterable, and it returns a tuple of the selected values; in your case, a tuple of size 1, with the value being the sequence.
Something like this will work -
for values in obj:
print(values[0])
If you queried for something else, so for example, if your query was select gene_name, sequence from genes where key=54321, then values in the above example will have two items.
If you are absolutely certain that only one result will be returned (or only want the first result), then you can use the fetchone method, and avoid the loop altogether.

How can I "fetch two" with python-mysql?

I have a table, and I want to execute a query that will return the values of two rows:
cursor.execute("""SELECT `egg_id`
FROM `groups`
WHERE `id` = %s;""", (req_id))
req_egg = str(cursor.fetchone())
print req_egg
The column egg_id has two rows it can return for that query, however the above code will only print the first result -- I want it to also show the second, how would I get both values?
Edit: Would there be any way to store each one in a separate variable, with fetchmany?
in this case you can use fetchmany to fetch a specified number of rows:
req_egg = cursor.fetchmany(2)
edit:
but be aware: if you have a table with many rows but only need two, then you should also use a LIMIT in your sql query, otherwise all rows are returned from the database, but only two are used by your program.
Call .fetchone() a second time, and it would return the next result.
Otherwise if you are 100% positively sure that your query would always return exactly two results, even if you've had a bug or inconsistent data in the database, then just do a .fetchall() and capture both results.
Try this:
Cursor.fetchmany(size=2)
Documentation for sqlite3 (which also implements dbapi): http://docs.python.org/library/sqlite3.html#sqlite3.Cursor.fetchmany

Categories