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
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.
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 ]
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"""
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'