now my error is like this
File "/home/bellvantage/Documents/openerp-7.0/openerp-7/openerp/addons/bpl/bpl.py", line 119, in _max_reg_no
res = cr.fetchone()[0]
TypeError: 'NoneType' object has no attribute '__getitem__'
I have a table called bpl_worker.there is a function i called in my python code.
def _max_reg_no(self, cr, uid, context=None):
res = {}
cr.execute("""
select COALESCE(register_no, 'W00001') as reg_no
from bpl_worker
where id in
(select coalesce(max(id),0) from bpl_worker)
""")
rows = cr.fetchall()
if len(rows) == 0:
return 'W00001'
else:
res = rows[0]
emp_no = str(res)
emp_int = emp_no[1:6]
emp_no_int = int(emp_int)
result = 'W' + (str(emp_no_int + 1).zfill(4))
return result
if table have at least one record then its worked and return records.in inital level can't get records of the if null message as output.
please help me to sort this issue
thanks
now my table if null issue ok.but after my record return as 'W00001'
then error comes at below point
res = cr.fetchone()[0]
First, the whole section:
CASE
WHEN register_no IS NULL
THEN 'Empty'
ELSE register_no
END
can be replaced with:
COALESCE(register_no, 'Empty')
Coalesce is a well known function to handle null values in rows. There is also an IFNULL function which serves same needs.
As far as I get your question, you would like to fetch records from an empty table (i.e. table containing no rows). This can't work. You may want to check for the number of records returned by the query first, this can be don either by examining cr.rowcount attribute, or by trying to fetch all rows and the inspecting the length of the resulting array:
rows = cr.fetchall()
if len(rows) == 0: return 'Empty'
Related
cur.execute("""
CREATE TEMPORARY VIEW bobby_view AS
SELECT heading1, heading2
FROM bobby
WHERE heading2 = %s; """, (variable,))
cur.execute("""
SELECT d1.heading1
FROM bobby_view d1
WHERE d1.heading1 >= ALL (
SELECT d2.heading1
FROM bobby_view d2);
""")
answer = cur.fetchone()[0]
This produces the error:
TypeError: 'NoneType' object is not subscriptable
This is the structure of my code. Variable was an integer entered as a parameter to a function and it has been casted as a string prior to the above code.
The second block of code finds the heading1 data that is the highest. I've tested this on its own and I am fairly confident it works. Because of this, I think the error comes from variable not being used in the view properly. Any help or advice would be greatly appreciated.
Try:
cur.execute("""
SELECT d1.heading1
FROM bobby_view d1
WHERE d1.heading1 >= ALL (
SELECT d2.heading1
FROM bobby_view d2);
""")
answer = cur.fetchone()
answer = answer[0] of answer else 'default'
you can refer the documentation here
fetchone returns the next row of a query result set and returns a single sequence, or None if no more rows are available, so if you are fetching the last row the error will occur. Try something like this,
answer = cur.fetchone()
while answer is not None:
print(answer)
answer = cur.fetchone()
Using Sqlite3. Let's say I have this empty table table with no rows. Not one row of data is inserted, completely empty.
c = conn.cursor()
test
-----------------
amount | date
query = "SELECT SUM (column1) FROM test WHERE date BETWEEN '"+blah+"' AND '"+blah+"'"
c.execute(query)
data = c.fetchall()
if data == None:
amountsum = 0
else:
amountsum = data
print(amountsum)
output = (100 - amountsum)
print(output)
When I print amountsum, all i get is (None,) which is not 0. For output, it would give me "TypeError: Unsupported operand type(s) for +: 'int' and 'NoneType'
How do set assign 0 to amountsum if date is a 'NoneType'
Because you use fetchall() data will be/is list with one element - tuple - (None,), when date not between the specific dates. So basically data is [(None,)]
That is why your if check does not work.
Use fetchone(), to get just one tuple.
query = "SELECT SUM(column1) FROM test WHERE date BETWEEN '"+blah+"' AND '"+blah+"'"
c.execute(query)
data = c.fetchone()
if data[0] is None:
amountsum = 0
else:
amountsum = data[0]
it's better to change your query and use COALESCE
query = "SELECT COALESCE(SUM(column1), 0) FROM test WHERE date BETWEEN '"+blah+"' AND '"+blah+"'"
c.execute(query)
data = c.fetchone()
amountsum = data[0]
Your code is not behaving as desired because a list of tuple instances representing database records returned by a query is returned by sqlite3.connect.cursor.fetchall(), in the case that no records are returned by the query an empty list will be returned.
The statement if data == None: will never pass in your script as [] != None.
You could apply the "autosum is query result or 0 if no results present in data" logic right after assignment of data using the following line.
autosum = 0 if not data else data[0][0]
Note how the above accesses the first value within the first tuple in the list data. If we simply wrote autosum = 0 if not data else data we would assign the entire list if any results are returned instead of the single returned value you seem to be trying to work with.
fetchone()
Since you are only seeking to access a single query result (at least as far as I can tell from the code you've shared) it would probably be an idea to use sqlite3.connect.cursor.fetchone() instead of sqlite3.cursor.fetchall(). This will return a tuple representing the first query result instead of the list of tuple instances as with fetchall().
data = c.fetchone()
autosum = 0 if not data else data[0]
I am using sqlalchemy ORM layer to communicate with RDS.
Here this is common function for all tables to filter row.
We pass table name, column to select, filters and date range.
filter = { "company_guid": "xxxx", "status": "Active"}
filter is dictionary which have key as column name and value is condition.
Which work fine
but know I want filter on status column where value can be Active or TempInActive
So now filter become filter = { "company_guid": "xxxx", "status": ["Active", "TempActive"}
It not working because value is list, not string.
I know can use result = session.query(Customers).filter(Customers.id.in_([1,3])) but in my scenario table name and column names are function arguments.
def get_items_withvalue(self, table_name, column_name=None, attribute_value=None,
columns_to_select=None, date_value=False, filters=None):
"""
#Summary: This method used to get data based on a condition.
#param table_name (string): This is the table_name
#param column_name (None/string): for the column_name
#param attribute_value (None/list/string): for the column_value
#params columns_to_select(None/list/string): columns to send in response
#params filters(None/dict): where clause for rows to be fetched
#return (list of dict): fetched rows or count from DB
"""
data = []
session = None
try:
# Get session which communicate with RDS
session = self.get_session()
table = str_to_class(table_name)
if columns_to_select:
data = []
else:
if isinstance(attribute_value, list):
data = (session.query(table)
.filter(getattr(table, column_name)
.in_(attribute_value))
.all())
elif date_value:
data = (session.query(table)
.filter(cast(getattr(table, column_name), Date)
== attribute_value)
.all())
elif filters:
## How to update following code to filter on list(in)
# filters is dictionary
data = (session.query(table).filter_by(**filters).all())
##
else:
data = (
session.query(table).filter(getattr(table, column_name)
== attribute_value).all()
)
except Exception as err:
self.logger.exception("Error fetching items ")
raise Exception(err)
finally:
if session:
session.close()
if columns_to_select:
return [row._asdict() for row in data]
return [object_as_dict(row) for row in data]
Can anyone help me to solve this?
One way is to construct query string and do eval, but which is not good way.
As you are using the ORM I'll assume that what you call table in the function is actually a mapped ORM class.
If I understand correctly, you want to be able to handle both cases where the values of filters may be either a scalar value, in which case you'd like to filter on equality, or a list of values, in which case you'd like to test for presence in the list using in_(). However, a complicating factor is that you cannot use the str keys of filters directly in filter(). Hopefully I've understood.
I think you can solve this neatly by using getattr to get the column attribs from the table object, a conditional list comprehension and then unpacking the list into .filter(), for example:
filters = {'a': 'scalar', 'and': ['collection', 'of', 'values']}
(
session.query(table).filter(
*[
getattr(table, k).in_(v)
if isinstance(v, list)
else getattr(table, k) == v
for k, v in filters.items()
]
)
)
This will produce the equivalent of orm_table_object.column_attrib == val if val is not a list, and orm_table_object.column_attrib.in_(val) if val is a list.
Extending the above answer just with a list of conditions
filters = [orm_table_object.field_name_1 == expected_value_1]
if expected_value_2 is not None:
filters.append(orm_table_object.field_name_2 == expected_value_2)
if expected_value_3 is not None:
filters.append(orm_table_object.field_name_3 == expected_value_3)
session.query(table).filter(
*[f for f in filters]
)
Im trying to save three values from SQLite in a Python list. All values are from a different column but in the same row. If the value is null I dont want to add it to the list. This is the code I wrote:
def create_list(self, chat):
list = []
for x in range(1, 3):
column_name = "list" + str(x)
value = c.execute("SELECT (?) FROM user WHERE (?) NOTNULL AND id = (?)", (column_name, column_name, chat)).fetchall()
if value != None:
list.append(value[0][0])
print(list)
Instead of printing the SQLite values in a list it just prints: ['list1', 'list2', 'list3'] (If one of the values in the table is null it doesnt print that one. For example if the value in column liste3 is null it just prints ['list1', 'list2'])
How can I fix this so that it saves the actual SQLite values in the list?
I had the same problem.
SQLite package ignores NULL values by default after fetching the data. you need to put a condition that prints 'Empty' or something when it faces NULL values. something like:
conn = sqlite3.connect("someDataBase.db")
db = conn.cursor()
db.execute('''
SELECT name, email
FROM person
WHERE name = 'some dude'
''')
result = db.fetchone()
if result is None: #if a value IS NULL
print 'Empty'
else:
var = result[0]
print var
How can be determined whether a record exists in a table? The way I tried was to do a SELECT query and then count the rows of the ResultSet using the following:
rows = session.execute("SELECT * FROM test_table WHERE id=%s", ([<id_here>]))
if len(rows) == 0:
print "Does not exist"
However, ResultSet does not support len. In another answer, they suggest to use SELECT COUNT(*) which in another reference is strongly discouraged. Is there a more standard way to do this?
You can simply do one of the following:
rows = session.execute("SELECT * FROM test_table WHERE id=%s", ([<id_here>]))
if not rows:
print "Does not exist"
Or, if selecting multiple rows you could iterate over the ResultSet with:
for row in rows:
do_something(row)
ResultSet also has a current_rows attribute which will be empty if none were returned.
See http://datastax.github.io/python-driver/api/cassandra/cluster.html#cassandra.cluster.ResultSet for more details on how to use the ResultSet.
Cassandra session.execute returns ResultSet object that contain current_rows attribute.
try folowing:
r = session.execute(f"SELECT * FROM test_table WHERE id = {some_id} limit 1")
if(len(r.current_rows) == 0):
# your code here