I am trying to retrieve a user from my sessions table in the database. In my unit test i get an error:
line 138, in test_session_user
self.assertEqual(nick_from_cookie, nick)
AssertionError: ('Bobalooba',) != 'Bobalooba'
I understand that this is because my code is returning a tuple when the test is comparing my return value against a string therefore it is not matching.
Is there a way for me to do this comparison using the tuple or is their a better way to query the result i need. Below is the table im using aswell as my function:
def session_user(db):
"""try to
retrieve the user from the sessions table
return usernick or None if no valid session is present
"""
cursor = db.cursor()
sessionid = bottle.request.get_cookie(COOKIE_NAME)
usernick = None
if sessionid:
cursor.execute("SELECT usernick FROM sessions WHERE sessionid=?", (sessionid,))
usernick = cursor.fetchone()
return usernick
Use
row = cursor.fetchone()
if row:
usernick, = row
Note the unpacking of the tuple.
Related
I write to see how I can get only one data to show by a print when I make a query in python, when I do the query it should only give me a number but I cannot show or access it.
def run_query(self, query, parameters = ()):
with sqlite3.connect(self.db_name) as conn:
cursor = conn.cursor()
result = cursor.execute(query, parameters)
conn.commit()
return result
def get_horarios(self):
query = 'SELECT hora FROM horarios where horario=1'
db_rows = self.run_query(query)
print(db_rows)
To show the first row in the results of the query:
print(db_rows.fetchone())
To show all of the results of the query:
print(db_rows.fetchall())
or
for row in db_rows.fetchall():
print(row)
The query always return a list. To access the first item, you can do:
print(db_rows[0])
I have gone through:
Error "Previous SQL was not a query" in Python?
MSSQL2008 - Pyodbc - Previous SQL was not a query
How to check if a result set is empty?
However none of them have resolved the issue.
The snippet from my db.py file is as follows:
result = cursor.execute(self.sql,self.params)
if result is None:
self.data = []
else:
self.data = [dict(zip([key[0] for key in cursor.description], row)) for row in result.fetchall()]
cnxn.close()
return self.data
This works for every SQL and stored procedure I have thrown at it except for this one
seq = request.form['seq']
s = 'EXEC sp_add ?, ?'
p = (udf.get_username(), int(seq))
l = Conn.testing(db="testingDatabase",sql=s,params=p)
I get the error:
Previous SQL was not a query
The SQL:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE sp_add
#user nvarchar(50),
#seq int
AS
BEGIN
SET NOCOUNT ON;
insert into tblName (userCol,seqCol) VALUES (#user,#seq)
END
GO
The stored procedure runs and the row gets inserted but the error shows up.
What I did instead was:
result = cursor.execute(self.sql,self.params)
cnxn.close()
return str(result)
This returns:
EXEC sp_add ?, ?
Why does it return that? Why does it return the statement I just passed to it?
In my SP, if I tag on a SELECT statement then the issue goes away.
Any suggestions other than the hack just mentioned?
According to the Python Database API PEP 249 specification, the return value of cursor.execute is not defined. So DB-APIs like pyodbc do not need to define consistent return value.
However, specifically for pyodbc, cursor.execute() returns a <pyodbc.Cursor> object which maintains the description attribute if object contains a value but will be None if an action command:
result = cursor.execute(self.sql, self.params)
if result.descripton is None:
self.data = []
else:
self.data = [
dict(zip([key[0] for key in cursor.description], row))
for row in
result.fetchall()
]
cnxn.close()
return self.data # METHODS INSIDE CLASSES DO NOT REQUIRE RETURN
Consider even a ternary operator:
result = cursor.execute(self.sql, self.params)
self.data = (
[
dict(zip([key[0] for key in result.description], row))
for row in result.fetchall()
]
if result.descripton is not None
else []
)
cnxn.close()
return self.data
I am trying to make a simple AWS Lambda function to get few rows from Amazon RDS(MySQL db) and return it in the json format.
If I try to append the object instance then I get error that object of type XXX is not json serializable. If I do something like below then I get only latest entry from the db. (This is unlike to what shown in https://hackersandslackers.com/create-a-rest-api-endpoint-using-aws-lambda/).
def save_events(event):
result = []
conn = pymysql.connect(rds_host,user=name,passwd=password,db=db_name,connect_timeout=5)
with conn:
cur = conn.cursor()
cur.execute("select * from tblEmployees")
rows = cur.fetchall()
for row in rows:
employee = Employee(row)
data['Id'] = employee.id
data['Name']= employee.name
result.append(data)
return result
def main(event, context):
data = save_events(event)
return {
"StatusCode":200,
"Employee": data
}
I understand that the contend of variable 'data' changes runtime and it affects on result.append(). I've 4 entries in table tblEmployees. The output of above gets 4 entries in the result but all the four entries are same (and equal to the latest record in the db).
The json.dumps() didn't work as the data is in the unicode format. I've already tried .toJSON() and byteify() and it didn't work.
Any help ?
You should re-create the data to avoid overriding old values:
for row in rows:
employee = Employee(row)
data = new Dict(Id=employee.id, Name=employee.name)
result.append(data)
I have a SQL database file which contains a multitude of columns, two of which are 'GEO_ID' and 'MED_INCOME'. I am trying to retrieve just the 'MED_INCOME' column data using the associated 'GEO_ID'. Here is what I thought would work:
import sqlite3 as db
def getIncome(censusID):
conn = db.connect('census.db')
c = conn.cursor()
c.execute("SELECT 'MED_INCOME' FROM censusDbTable WHERE GEO_ID = %s" % (censusID)
response = c.fetchall()
c.close()
conn.close()
return response
id = 60014001001
incomeValue = getIncome(id)
print("incomeValue: ", incomeValue)
Which results in:
incomeValue: [('MED_INCOME',)]
I thought that I had used this method before when attempting to retrieve the data from just one column, but this method does not appear to work. If I were to instead write:
c.execute("SELECT * FROM censusDbTable WHERE GEO_ID = %s" % (censusID)
I get the full row's data, so I know the ID is in the database file.
Is there something about my syntax that is causing this request to result in an empty set?
Per #Ernxst comment, I adjusted the request to:
c.execute("SELECT MED_INCOME FROM censusDbTable WHERE GEO_ID = %s" % (censusID)
Removing the quotes around the column ID, which solved the problem.
I have been using Psycopg2 to read stored procedures from Postgres successfully and getting a nice tuple returned, which has been easy to deal with. For example...
def authenticate(user, password):
conn = psycopg2.connect("dbname=MyDB host=localhost port=5433 user=postgres password=mypwd")
cur = conn.cursor()
retrieved_pwd = None
retrieved_userid = None
retrieved_user = None
retrieved_teamname = None
cur.execute("""
select "email", "password", "userid", "teamname"
from "RegisteredUsers"
where "email" = '%s'
""" % user)
for row in cur:
print row
The row that prints would give me ('user#gmail.com ', '84894531656894hashedpassword5161651165 ', 36, 'test ')
However, when I run the following code to read a row of fixtures with a Stored Procedure, I get (what looks to me like) an unholy mess.
def get_from_sql(userid):
conn = psycopg2.connect("dbname=MyDB host=localhost port=5433 user=postgres password=pwd")
fixture_cursor = conn.cursor()
callproc_params = [userid]
fixture_cursor.execute("select sppresentedfixtures(%s)", callproc_params)
for row in fixture_cursor:
print row
The resulting output:
('(5,"2015-08-28 21:00:00","2015-08-20 08:00:00","2015-08-25 17:00:00","Team ",,"Team ",,"Final ")',)
I have researched the cursor class and cannot understand why it outputs like this for a stored procedure. When executing within Postgres, the output is in a perfect Tuple. Using Psycopg2 adds onto the tuple and I don't understand why?
How do I change this so I get a tidy tuple? What am I not understanding about the request that I am making that gives me this result?
I have tried the callproc function and get an equally unhelpful output. Any thoughts on this would be great.
This is because you're SELECTing the result of the function directly. Your function returns a set of things, and each "thing" happens to be a tuple, so you're getting a list of stringified tuples back. What you want is this:
SELECT * FROM sppresentedfixtures(...)
But this doesn't work, because you'll get the error:
ERROR: a column definition list is required for functions returning "record"
The solution is to return a table instead:
CREATE OR REPLACE FUNCTION sppresentedfixtures(useridentity integer) RETURNS TABLE(
Fixture_No int,
Fixture_Date timestamp,
...
) AS
$BODY$
select
"Fixtures"."Fixture_No",
"Fixtures"."Fixture_Date",
...
from "Fixtures" ...
$BODY$ LANGUAGE sql