i'm making database to fill out a table with variable - python

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,))

Related

How can i run all my code in one function

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.

Transfering Data in MS Access Using Python

I have an ever growing and changing database that reflects a permits passed by the State and EPA.
As the database changes and updates I need to transfer the relevant information.
The script does two things; first it checks which fields are the same and creates a list of fields and data that will be inserted into the new database. Second to insert the data into the new database.
Problem is I cannot get it to insert. I have matched everything like it says online in various ways but i get error ('42000', '[42000] [Microsoft][ODBC Microsoft Access Driver] Syntax error in INSERT INTO statement. (-3502) (SQLExecDirectW)').
I cannot figure out how to prevent it.
Code:
import pyodbc
importDatabase = r"J:\ENVIRO FIELD\AccessDatabases\MS4\MS4 Town Databases\~Template\MS4_Apocalypse Import DEV 1.accdb"
"Create the Import Database Connection"
connectionImport = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=%s;' %(importDatabase))
cursorImport = connectionImport.cursor()
"####---Outfall Section---####"
"Import the outfall names into the new database"
tbl = "tbl_Outfall_1_Profile"
exportList = []
importList = []
for row in cursorImport.columns(table = "tblExportMigration_Outfall_1_Profile"):
field = row.column_name
exportList.append(field)
for row in cursorImport.columns(table = "tbl_Outfall_1_Profile"):
field = row.column_name
importList.append(field)
matchingList = []
for field in exportList:
if field != "outfallID":
if field in importList:
matchingList.append(field)
else:
continue
sqlValue = ""
for field in matchingList:
sqlValue += "[%s], " %(field)
sqlValue = sqlValue[:-2]
sql = "SELECT %s from %s" %(sqlValue, "tblExportMigration_Outfall_1_Profile")
for rowA in cursorImport.execute(sql):
tupleList = list(rowA)
tupleList = ["" if i == None else i for i in tupleList]
tupleValues = tuple(tupleList)
sqlUpdate = """INSERT INTO tbl_Outfall_1_Profile (%s) Values %s;""" %(sqlValue, tupleValues)
cursorImport.execute(sqlUpdate)
cursorImport.close()
This is the sql string I create
"INSERT INTO tbl_Outfall_1_Profile ([profile_OutfallName], [profile_HistoricalName1], [profile_HistoricalName2], [profile_HistoricalName3], [profile_HistoricalName4]) Values ('756', '', '', '', '');"
Taking what #Gord Thompson said I was actually able to create a dynamic parameter flow
First created a module to create the ?
def Defining_Paramters(length):
parameterString = ""
for x in range(1,length):
parameterString += "?, "
parameterString += "?"
return parameterString
Then stuck it into the string for the sql update
sqlUpdate = sqlUpdate = "INSERT INTO %s (%s) Values (%s);" %(table, sqlFrameworkSubStr, parameters)
Run the cursor and commit it
cursorTo.execute(sqlUpdate, (dataTuple))
connectionTo.commit()
It would seem that you have to create the query in its entirety then have your data in tuple format for entry
This is the sql string [I think] I create
Try this:
sqlUpdate = """INSERT INTO tbl_Outfall_1_Profile (%s) Values (%s);""" %(sqlValue, tupleValues)
or perhaps:
sqlUpdate = "INSERT INTO tbl_Outfall_1_Profile (%s) Values (%s);" %(sqlValue, tupleValues)

Updating results from a mysql-connector fetchall

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.

Python MySQL WHERE Statement

Ok, I am trying to figure out how to make my variable passed to my method, which that is the easy part. My main problem that I am having is that I need that value of that variable in my method equal to the value in the WHERE Statement.
I was told to use %s to equal the value being passed, but MariaDB doesn't like the syntax. Any help would be greatly appreciated.
def ERRORDISPLAY(ErrorTpye):
#value = ErrorType
conn = connection.MySQLConnection(user = 'user', password = '123456',
host = 'localhost', database= 'HomeConnect')
cursor = conn.cursor()
query = ("SELECT errNumber, description FROM Error_List WHERE errNumber = %s value %s")
num = ErrorType
cursor.execut(query,(num))
for (description) in cursor:
return print(num, description)
ERRORDISPLAY(1)
I got it all figured out. I had to cast the integer to a string. for some reason the MariaDB for Pi W does not like certain syntax. So it should look like this:
def ERRORDISPLAY(ErrorTpye):
conn = connection.MySQLConnection(user = 'user', password = '123456',
host = 'localhost', database= 'HomeConnect')
cursor = conn.cursor()
value = ErrorList
query = ("SELECT errNumber, description FROM Error_List WHERE errNumber =" + str(value))
cursor.execute(query, (value))
for (description) in cursor:
return print(num, description)
ERRORDISPLAY(1)

Python MySQLdb: mysql_exceptions.ProgrammingError: (1064)

I am trying to retrieve data from MySQL. Unfortunately, I am getting the error s below:
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
version fo r the right syntax to use near '1=,-5000,1)) AND
(IF(3=,5000,3)))at line 1")
volumeMin and volumeMax I put as integer. In actual, it can be float. How can I fix the error?
import MySQLdb
import MySQLdb.cursors
db = MySQLdb.connect(host='xxx.mysql.pythonanywhere-services.com',user='xxx',passwd='xxx',db='xxx$default',cursorclass=MySQLdb.cursors.DictCursor)
curs = db.cursor()
name ='G%'
volumeMin = 1
volumeMax = 3
#request args was initially want to retrieve data from external app
#but eventually found that the problem is in MySQL request
"""name = request.args['name']
volumeMin = request.args['volumeMin']
volumeMax = request.args['volumeMax']
"""
query0 = "SELECT * FROM KLSE WHERE Stock LIKE %s AND "
query2 = "(Volume_changes_pc BETWEEN (IF %s='_',-5000,%s)) AND (IF(%s='_',5000,%s)))"
query = query0+query2
input = name,volumeMin,volumeMin,volumeMax,volumeMax
print query
print input
print (query,(input))
curs.execute(query,(input))
a = curs.fetchall()
output of print (query,(input))
('SELECT * FROM KLSE WHERE Stock LIKE %s AND (Volume_changes_pc BETWEEN (IF %s=_,-5000,%s)) AND (IF(%s=_,5000,%s))) AND MACD LIKE %s ', ('G%', 1, 1
, 3, 3, 'H'))
solved
query2 = "(Volume_changes_pc BETWEEN (IF (%s='_',-5000,%s)) AND (IF(%s='_',5000,%s)))"
miss out a bracket

Categories