python oracle SQL query conversion - python

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.

Related

Python SQLite3 fetch raw?

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

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']))

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

how to count value returned from select query in python

I want to count the total number of rows returned by query. I am able to retrieved rows returned by query but what if i need to work in case when no data exits. that is when query returns no va from database.
the code i used to solve this problem is :
try:
cur.execute(query)
id = cur.fetchone()[0]
if(id is None):
return '-1'
else:
return id
But this doenst help when no values is returned selected from query.(when condition doesnt meet criteria defined in select statement)
cur.fetchall() will give you a sequence of all the rows. You can look at the length of that sequence to see if any rows were returned. This works for small result sets, but may not be ideal for queries that return large amounts of data.
Alternatively, you can look at cur.rowcount. Rowcount will return the number of rows in the query, or -1 if the number cannot be determined. It is up to the implementation to set rowcount; several popular python database modules (most notably sqlite3), do not set rowcount for all queries. For modules that do not set rowcount, the only way to count the number of result rows is to load the full result set into memory.

Python: Number of rows affected by cursor.execute("SELECT ...)

How can I access the number of rows affected by:
cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'")
Try using fetchone:
cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'")
result=cursor.fetchone()
result will hold a tuple with one element, the value of COUNT(*).
So to find the number of rows:
number_of_rows=result[0]
Or, if you'd rather do it in one fell swoop:
cursor.execute("SELECT COUNT(*) from result where server_state='2' AND name LIKE '"+digest+"_"+charset+"_%'")
(number_of_rows,)=cursor.fetchone()
PS. It's also good practice to use parametrized arguments whenever possible, because it can automatically quote arguments for you when needed, and protect against sql injection.
The correct syntax for parametrized arguments depends on your python/database adapter (e.g. mysqldb, psycopg2 or sqlite3). It would look something like
cursor.execute("SELECT COUNT(*) from result where server_state= %s AND name LIKE %s",[2,digest+"_"+charset+"_%"])
(number_of_rows,)=cursor.fetchone()
From PEP 249, which is usually implemented by Python database APIs:
Cursor Objects should respond to the following methods and attributes:
[…]
.rowcount
This read-only attribute specifies the number of rows that the last .execute*() produced (for DQL statements like 'select') or affected (for DML statements like 'update' or 'insert').
But be careful—it goes on to say:
The attribute is -1 in case no .execute*() has been performed on the cursor or the rowcount of the last operation is cannot be determined by the interface. [7]
Note:
Future versions of the DB API specification could redefine the latter case to have the object return None instead of -1.
So if you've executed your statement, and it works, and you're certain your code will always be run against the same version of the same DBMS, this is a reasonable solution.
The number of rows effected is returned from execute:
rows_affected=cursor.execute("SELECT ... ")
of course, as AndiDog already mentioned, you can get the row count by accessing the rowcount property of the cursor at any time to get the count for the last execute:
cursor.execute("SELECT ... ")
rows_affected=cursor.rowcount
From the inline documentation of python MySQLdb:
def execute(self, query, args=None):
"""Execute a query.
query -- string, query to execute on server
args -- optional sequence or mapping, parameters to use with query.
Note: If args is a sequence, then %s must be used as the
parameter placeholder in the query. If a mapping is used,
%(key)s must be used as the placeholder.
Returns long integer rows affected, if any
"""
In my opinion, the simplest way to get the amount of selected rows is the following:
The cursor object returns a list with the results when using the fetch commands (fetchall(), fetchone(), fetchmany()). To get the selected rows just print the length of this list. But it just makes sense for fetchall(). ;-)
print len(cursor.fetchall)
# python3
print(len(cur.fetchall()))
To get the number of selected rows I usually use the following:
cursor.execute(sql)
count = len(cursor.fetchall())
when using count(*) the result is {'count(*)': 9}
-- where 9 represents the number of rows in the table, for the instance.
So, in order to fetch the just the number, this worked in my case, using mysql 8.
cursor.fetchone()['count(*)']

Categories