Setting variable to 0 using if statement - python

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]

Related

Converting PYODBC output into an int

Pulling data from a SQL query that gives me 1 number that is stored in a PYODBC row. I want to then add that number to another variable in the file. Pseudocode below -
prev = 5
cursor.execute("select statement")
pulledNumber = cursor.fetchall()
value = [row[2] for row in pulledNumber]
final = prev + value
Getting a type error (list and int operation). Tried to cast the list to an int a few different ways but could not get it to work

Array Outputting result set with the same amount of rows in a sql database

I have a query that reaches into a MySQL database and grabs row data that match the column "cab" which is a variable that is passed on from a previous html page. That variable is cabwrite.
SQL's response is working just fine, it queries and matches the column 'cab' with all data point in the rows that match id cab.
Once that happens I then remove the data I don't need line identifier and cab.
The output from that is result_set.
However when I print the data to verify its what I expect I'm met with the same data for every row I have.
Example data:
Query has 4 matching rows that is finds
This is currently what I'm getting:
> data =
> ["(g11,none,tech11)","(g2,none,tech13)","(g3,none,tech15)","(g4,none,tech31)"]
> ["(g11,none,tech11)","(g2,none,tech13)","(g3,none,tech15)","(g4,none,tech31)"]
> ["(g11,none,tech11)","(g2,none,tech13)","(g3,none,tech15)","(g4,none,tech31)"]
> ["(g11,none,tech11)","(g2,none,tech13)","(g3,none,tech15)","(g4,none,tech31)"]
Code:
cursor = connection1.cursor(MySQLdb.cursors.DictCursor)
cursor.execute("SELECT * FROM devices WHERE cab=%s " , [cabwrite])
result_set = cursor.fetchall()
data = []
for row in result_set:
localint = "('%s','%s','%s')" % ( row["localint"], row["devicename"], row["hostname"])
l = str(localint)
data.append(l)
print (data)
This is what I want it too look like:
data = [(g11,none,tech11),(g2,none,tech13),(g3,none,tech15),(g4,none,tech31)]
["('Gi3/0/13','None','TECH2_HELP')", "('Gi3/0/7','None','TECH2_1507')", "('Gi1/0/11','None','TECH2_1189')", "('Gi3/0/35','None','TECH2_4081')", "('Gi3/0/41','None','TECH2_5625')", "('Gi3/0/25','None','TECH2_4598')", "('Gi3/0/43','None','TECH2_1966')", "('Gi3/0/23','None','TECH2_2573')", "('Gi3/0/19','None','TECH2_1800')", "('Gi3/0/39','None','TECH2_1529')"]
Thanks Tripleee did what you recommended and found my issue... legacy FOR clause in my code upstream was causing the issue.

Assign elements while you loop inside a function or with append automatically

I was wondering if you could help me with my problem
I am trying to create a function that gets data frames based on SQL QUERY.
My function is:
def request_data(str,conn):
cur = conn.cursor()
cur.execute(str)
data = pd.read_sql_query(str, conn)
return data
When I try to apply my function using append method, I get what I expect as a result!
Tables_to_initialize = ['sales', 'stores', 'prices']
Tables = []
for x in Tables_to_initialize:
Tables.append(request_data("SELECT * FROM {i} WHERE d_cr_bdd =
(SELECT MAX(d_cr_bdd) FROM {i} ) ; ".format(i = x),conn))
But,
Tables is a list that contains all the sorted data frames based on my query, what i really want to do is to assign every element in my list tables to it's name, for example
Tables_to_initialize[0] = 'sales'
and i want to Tables[0] to be sales as object (data frame).
Is there any method to assign objects inside the function or with append automatically? Or any other solution?
I really appreciate your help
Best regards,
To get a list of objects based on given query.
table = [requested_data("SELECT * FROM {i} WHERE d_cr_bdd = (SELECT MAX(d_cr_bdd) FROM {i}".format(i)) for i in Tables_to_initialize ]

Converting a tuple into an integer in python 3?

I have a tuple with a single value that's the result of a database query (it gives me the max ID # currently in the database). I need to add 1 to the value to utilize for my subsequent query to create a new profile associated with the next ID #.
Having trouble converting the tuple into an integer so that I can add 1 (tried the roundabout way here by turning the values into a string and then turning into a int). Help, please.
sql = """
SELECT id
FROM profiles
ORDER BY id DESC
LIMIT 1
"""
cursor.execute(sql)
results = cursor.fetchall()
maxID = int(','.join(str(results)))
newID = maxID + 1
If you are expecting just the one row, then use cursor.fetchone() instead of fetchall() and simply index into the one row that that method returns:
cursor.execute(sql)
row = cursor.fetchone()
newID = row[0] + 1
Rather than use an ORDER BY, you can ask the database directly for the maximum value:
sql = """SELECT MAX(id) FROM profiles"""

How to Null check in Postgre fresh table?

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'

Categories