My python code doesnt work. I get an output for only success mysql connection.
I want to print group id, hostname and other variables. The only output i get is
('Connected to MySQL Server version ', u'5.7.36-0ubuntu0.18.04.1')
("You're connected to database: ")
I cannot print group id or anything else. Im a newbie in python :(
import os
import mysql.connector
import json
execfile("/home/manager/test/mysqlconnector.py")
active_ip = ""
hostname = ""
group_id = 0
def my_funciton():
query = "select value_oid from snmp_trap where name_oid = '1.3.6.1.4.1.14823.2.3.3.1.200.1.17.0'"
cursor = connection.cursor(dictionary=True)
cursor.execute(query)
mac = cursor.fetchone()
mac_string = mac.values()
mac_str = json.dumps(mac_string)
mac_ = mac_str.replace(':','')
mac_ = mac_.replace('"','')
mac_ = mac_.replace(']','')
mac_ = mac_.replace('[','')
return mac_
active_mac = my_function()
query = "select epp_active_ip, epp_hostname, epp_group_id from epp_inventory where epp_active_mac = + 'active_mac.upper()'"
cursor = connection.cursor(dictionary=True)
cursor.execute(query)
rows = cursor.fetchall()
#active_ip = ""
#hostname = ""
#group_id = 0
for row in rows:
active_ip = row["epp_active_ip"]
hostname = row["epp_hostname"]
group_id = row["epp_group_id"]
print(group_id)
query = "select wmic_id from group_wmic where group_id = " + str(group_id)
cursor = connection.cursor(dictionary=True)
cursor.execute(query)
wmic_ids = cursor.fetchall()
for row in wmic_ids:
query = "select command_line from wmic_commands where id = " + row["wmic_id"]
cursor = connection.cursor(dictionary=True)
cursor.execute(query)
command_line = cursor.fetchone()
os.system(command_line)
os.system("ls -al")
#os.system(command)
my_funciton()
Apart from naming and indentation issues, which you should really fix, because it will make your code a nightmare to maintain - the issue is quite simple:
Consider:
def some_function():
print('this prints')
return
print('this does not')
Your code has the exact same problem. In your function my_funciton, you have the following line:
return mac_
Nothing after that will ever execute. You need to put the return statement in the position of the function's code where you expect it to actually return. You cannot put it just anywhere and expect the function to execute the rest of the code.
Related
import pymysql
from datetime import datetime
db = pymysql.connect(host = "localhost", user = "root", password = "mariadb", charset = "utf8");
cursor = db.cursor();
nm = 'park dong ju'
temp = 36.5
n_route = '->podium',
if nm != "" and temp != 0:
cursor.execute("USE SD;")
select_name ="SELECT name FROM PI WHERE name = '%s'"
select_route = "SELECT route FROM PI WHERE name = '%s'"
cursor.execute(select_name,(nm,))
PI_name = cursor.fetchone()
cursor.execute(select_route,(nm,))
PI_route = cursor.fetchone()
db.commit()
str_route = str(PI_route)
route = str_route + n_route
current_time = datetime.now()
insert_er = "INSERT INTO ER(name,temp,route,time) VALUES('%s',%.2f,'%s','%s')"
cursor.execute(insert_er,(nm,tmep,route,current_time))
name = ""
temp = 0
db.commit()
db.close()
this is my code
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'park_dong_ju''' at line 1")
this is error about code
When you use MySql placeholders, you don´t need to format them and don´t need tu use quotation marks. The MySql cursor will try to convert your data types. You can change your query as:
insert_er = "INSERT INTO ER(name,temp,route,time) VALUES(%s,%s,%s,%s)"
cursor.execute(insert_er,(nm,tmep,route,current_time))
And you can modify your first queries too, and remove your quotation marks:
select_name ="SELECT name FROM PI WHERE name = %s"
select_route = "SELECT route FROM PI WHERE name = %s"
cursor.execute(select_name,(nm,))
PI_name = cursor.fetchone()
cursor.execute(select_route,(nm,))
import sqlite3
import traceback
from time import sleep
import mysql.connector
def check_user(user_id):
conn = mysql.connector.connect(host='localhost', database='online', user='root1', password='rootRRR111_')
cur = conn.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS online(id INT, last_online_date TEXT)')
conn.commit()
select = "SELECT * FROM online WHERE id = %s LIMIT 0, 1"
result = cur.execute(select, (user_id,))
if result is None:
insert = ('INSERT INTO online (id, last_online_date) VALUES (%s, %s)')
cur.reset()
cur.execute(insert, (user_id, online_time))
conn.commit()
def update_online_status(user_id, online_time):
conn = mysql.connector.connect(host='localhost', database='online', user='root1', password='rootRRR111_')
cursor = conn.cursor()
select = 'SELECT last_online_date FROM online WHERE id = %s'
result = cursor.execute(select, (user_id,))
old_online = result
online_time = f'{old_online},{online_time}'
cursor.reset()
cursor.execute('UPDATE online SET last_online_date = %s WHERE id = %s', (online_time, user_id))
conn.commit()
app = Client("my_account")
app.start()
while True:
try:
with open('ids.ini', 'r') as file:
users = file.read().splitlines()
for user in users:
result = app.get_users(user)
user_id = result['id']
if result['status'] == 'offline':
unix_timestamp = float(result['last_online_date'])
local_timezone = tzlocal.get_localzone()
local_time = datetime.fromtimestamp(unix_timestamp, local_timezone)
online_time = local_time.strftime("%Y/%m/%d %H:%M:%S")
elif result['status'] == 'online':
now = datetime.now()
online_time = now.strftime("%Y/%m/%d %H:%M:%S")
check_user(user_id)
update_online_status(user_id, online_time)
# sleep(300)
except Exception:
traceback.print_exc()
continue
app.stop()
I am writing a program that would read the online status of a user in telegram.
Instead of writing online to an existing user, a huge number of identical rows appear in the database.
Example:
Table with repetitions
When I try to fix something, there are a lot of errors.
mysql.connector.errors.programmingerror: not all parameters were used in the sql statement
mysql.connector.errors.internalerror: unread result found
and other...
Pls help!!
I'm trying to select certain records from the civicrm_address table and update the geocode columns. I use fetchall to retrieve the rows then, within the same loop, I try to update with the results of the geocoder API, passing the civicrm_address.id value in the update_sql statement.
The rowcount after the attempted update and commit is always -1 so I am assuming it failed for some reason but I have yet to figure out why.
import geocoder
import mysql.connector
mydb = mysql.connector.connect(
[redacted]
)
mycursor = mydb.cursor(dictionary=True)
update_cursor = mydb.cursor()
sql = """
select
a.id
, street_address
, city
, abbreviation
from
civicrm_address a
, civicrm_state_province b
where
location_type_id = 6
and
a.state_province_id = b.id
and
street_address is not null
and
city is not null
limit 5
"""
mycursor.execute(sql)
rows = mycursor.fetchall()
print(mycursor.rowcount, "records selected")
for row in rows:
address_id = int(row["id"])
street_address = str(row["street_address"])
city = str(row["city"])
state = str(row["abbreviation"])
myaddress = street_address + " " + city + ", " + state
g = geocoder.arcgis(myaddress)
d = g.json
latitude = d["lat"]
longitude = d["lng"]
update_sql = """
begin work;
update
civicrm_address
set
geo_code_1 = %s
, geo_code_2 = %s
where
id = %s
"""
var=(latitude, longitude, address_id)
print(var)
update_cursor.execute(update_sql, var, multi=True)
mydb.commit()
print(update_cursor.rowcount)
mycursor.close()
update_cursor.close()
mydb.close()
Here is a simpler script:
I have executed the update_sql statement directly in the MySQL workbench and it succeeds. It is not working from Python.
import geocoder
import mysql.connector
try:
mydb = mysql.connector.connect(
[redacted]
)
mycursor = mydb.cursor(dictionary=True)
update_cursor = mydb.cursor()
update_sql = """
begin work;
update
civicrm_address
set
geo_code_1 = 37.3445
, geo_code_2 = -118.5366074
where
id = 65450;
"""
update_cursor.execute(update_sql, multi=True)
mydb.commit()
print(update_cursor.rowcount, "row(s) were updated")
except mysql.connector.Error as error:
print("Failed to update record to database: {}".format(error))
mydb.rollback()
finally:
# closing database connection.
if (mydb.is_connected()):
mydb.close()
I have it working now. I did remove the "begin work" statement but not the multi=True and it wouldn't work. Later I removed the multi=True statement and it works.
I am using python 2.7 with sqlite3
I've created an empty table to and a function that checks if the table is empty it gets the mac address of the current pc and stores it at the table, it works every time the program work, then if the table is not empty it calls another function that gets the current mac and compares it to the one stored in the table , then closes the program if its not the same ,,
Here is the code :
def active():
from uuid import getnode as get_mac
mac = get_mac()
name = 666
conn = sqlite3.connect('storage/container.db')
conn.row_factory = lambda c, row: row[0]
c = conn.cursor()
c.execute("SELECT COUNT(*) FROM mac")
count = c.fetchall()[0]
conn.close()
if count == 0:
conn = sqlite3.connect('storage/container.db')
conn.row_factory = lambda c, row: row[0]
c = conn.cursor()
c.execute("INSERT INTO mac (name, macAddress) VALUES (?, ?)", (name, mac, ))
conn.commit()
conn.close()
else:
checking()
def checking():
from uuid import getnode as get_mac
mac = get_mac()
conn = sqlite3.connect('storage/container.db')
conn.row_factory = lambda c, row: row[0]
c = conn.cursor()
c.execute("SELECT macAddress FROM mac WHERE name = 666")
table_mac = c.fetchall()[0]
if mac == table_mac:
critical_title1 = 'أهلاً بك '
critical_title = critical_title1.decode('utf-8')
critical_msg1 = "تم تأكيد صلاحية النسخة للإستخدام "
critical_msg = critical_msg1.decode('utf-8')
QtGui.QMessageBox.information(mainWindow, critical_title, critical_msg)
else:
critical_title1 = 'خطأ'
critical_title = critical_title1.decode('utf-8')
critical_msg1 = "لا يمكنك إستخدام البرنامج من دون شراء نسختك الخاصة"
critical_msg = critical_msg1.decode('utf-8')
QtGui.QMessageBox.critical(mainWindow, critical_title, critical_msg)
sys.exit()
everything goes fine and the program already catches the mac address then add it to the table, but then, in all cases, it shows the error that closes the program after it .. ignoring the if-else statement that should stop the error from being showed
i think the problem is here :
if mac == table_mac:
critical_title1 = 'أهلاً بك '
critical_title = critical_title1.decode('utf-8')
critical_msg1 = "تم تأكيد صلاحية النسخة للإستخدام "
critical_msg = critical_msg1.decode('utf-8')
QtGui.QMessageBox.information(mainWindow, critical_title, critical_msg)
else:
critical_title1 = 'خطأ'
critical_title = critical_title1.decode('utf-8')
critical_msg1 = "لا يمكنك إستخدام البرنامج من دون شراء نسختك الخاصة"
critical_msg = critical_msg1.decode('utf-8')
QtGui.QMessageBox.critical(mainWindow, critical_title, critical_msg)
sys.exit()
Note
the main problem that there is no traceback error
it just shows the last else statement despite the condition if mac == table_mac: is met
The problem was that I tried to call the 2nd function from inside the first one I just changed
else:
checking()
to pass and then add autorun command for both functions and it works great
active()
checking()
def websvc(currency):
db = MySQLdb.connect("localhost", "root", "aqw", "PFE_Project")
cursor = db.cursor()
sql = "SELECT * FROM myform_composantsserveur"
try:
cursor.execute(sql)
results = cursor.fetchall()
currency_in = currency
req = urllib2.urlopen('http://rate-exchange.appspot.com/currency?from=USD&to=%s') % (currency_in)
req1 = req.read()
rate = int(req1['rate'])
# rate = 0.77112893299999996
servers = []
for row in results:
result = {}
result['1'] = row[1]
result['3'] = int(row[2])
result['4'] = int(row[3])
result['5'] = int(row[4])
result['6'] = row[5]
result['7'] = int(row[6])
result['8'] = row[7]
result['9'] = row[8]
p = rate * calculations_metric (int(row[2]), int(row[3]), int(row[4]), int(row[6]), row[7])
result['2'] = p
keys = result.keys()
keys.sort()
servers.append(result)
except:
print "Error: unable to fetch data"
db.close()
return servers
but i have this error while compiling the code :
Exception Type: UnboundLocalError
Exception Value: local variable
'servers' referenced before assignment
Exception Location: /home/amine/PFE Directory/mysite1/myform/Webservice.py in websvc, line 43 Python Executable: /usr/bin/python2.7
this code works normally before i added a parameter in this function
Your code not able to reach servers initialization and that is why you getting error. Simply move initialization before try..except. Change this way:
def websvc(currency):
db = MySQLdb.connect("localhost", "root", "aqw", "PFE_Project")
cursor = db.cursor()
sql = "SELECT * FROM myform_composantsserveur"
servers = []
try:
cursor.execute(sql)
results = cursor.fetchall()
currency_in = currency
req = urllib2.urlopen('http://rate-exchange.appspot.com/currency?from=USD&to=%s') % (currency_in)
req1 = req.read()
rate = int(req1['rate'])
# rate = 0.77112893299999996
for row in results:
result = {}
result['1'] = row[1]
result['3'] = int(row[2])
result['4'] = int(row[3])
result['5'] = int(row[4])
result['6'] = row[5]
result['7'] = int(row[6])
result['8'] = row[7]
result['9'] = row[8]
p = rate * calculations_metric (int(row[2]), int(row[3]), int(row[4]), int(row[6]), row[7])
result['2'] = p
keys = result.keys()
keys.sort()
servers.append(result)
except:
print "Error: unable to fetch data"
db.close()
return servers
I see the problem now you have edited it to add the missing parts. It's the exception handler.
If you have an error after try and before servers=[] it will jump to the except clause, then see return servers and fail.
You might want to use a list(), instead of using a dict() to emulate a list ...
You can make the empty variable also in the try block if you check against the globals() variables any time after the try block. This is no game changer in this code since making a new empty list will never fail, but I could use it to have the opening of a connection into the try block so that it would be caught in the exception, and I could close that object in the finally block without having to make an empty object before the try/except/finally block (tested).
def websvc(currency):
db = MySQLdb.connect("localhost", "root", "aqw", "PFE_Project")
cursor = db.cursor()
sql = "SELECT * FROM myform_composantsserveur"
try:
servers = []
cursor.execute(sql)
results = cursor.fetchall()
currency_in = currency
req = urllib2.urlopen('http://rate-exchange.appspot.com/currency?from=USD&to=%s') % (currency_in)
req1 = req.read()
rate = int(req1['rate'])
# rate = 0.77112893299999996
for row in results:
result = {}
result['1'] = row[1]
result['3'] = int(row[2])
result['4'] = int(row[3])
result['5'] = int(row[4])
result['6'] = row[5]
result['7'] = int(row[6])
result['8'] = row[7]
result['9'] = row[8]
p = rate * calculations_metric (int(row[2]), int(row[3]), int(row[4]), int(row[6]), row[7])
result['2'] = p
keys = result.keys()
keys.sort()
servers.append(result)
except:
print "Error: unable to fetch data"
db.close()
if 'servers' in globals():
return servers
else:
return []
This is untested. If it crashes at servers.append(result), try if 'servers' in globals(): right before that as well. Which would blow up the code of the try block, therefore, I hope that it is not needed, and in my example, I also did not have to do that when I used the called connection afterwards in the try block.
Side remark: append() makes a full copy. Try servers.extend([result]) instead if you grow a large list (not likely if you just count up just a few servers).