Python MySQL WHERE Statement - python

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)

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.

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

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

Query function suddenly returning `None` instead of the item it should be retruning

I did some minor refactoring to some working code. All I did was add 2 functions to clean up how input and it's assignment was handled. I did not change anything about the query_pswd_by_name function but now it doesn't return the password, it returns None. Everything else works perfectly. Any ideas what is going on? Here is the code:
import secrets
import string
import sqlite3
import pyperclip
import optparse
#CREATE PASSWORD OF GIVEN LENGTH
def get_pass(length):
return "".join(secrets.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits + string.punctuation) for x in range(length))
def get_pass_length():
length = int(input("Enter the length of password: "))
password= get_pass(length)
print(password)
pyperclip.copy(password)
print('Password copied to clipboard')
def create_and_store_pwsd():
password = get_pass_length()
name = str(input("Enter name for password: "))
#CREATE DATABASE CONNECTION
conn = sqlite3.connect("managerDB.db")
#CREATE CURSOR OBJECT
c = conn.cursor()
#CREATE TABLE IN DISK FILE BASED DATABASE
c.execute("""CREATE TABLE IF NOT EXISTS password_table (
name TEXT,
pswd TEXT
)""")
#c.execute("DELETE FROM password_table")
c.execute("INSERT INTO password_table (name, pswd) VALUES (?, ?)", (name, password))
#COMMIT CHANGES
conn.commit()
conn.close()
def query_pswd_by_name(name):
conn = sqlite3.connect('managerDB.db')
c = conn.cursor()
query_password = "SELECT pswd FROM password_table WHERE name = ?"
c.execute(query_password,(name,))
result = c.fetchall()
for row in result:
pyperclip.copy(str(row[0]))
print("Password copied to clipboard")
print(str(row[0]))
conn.commit()
conn.close()
def input_name_and_query():
name = input('Name of password you wish to query: ')
query_pswd_by_name(name)
create_and_store_pwsd()
input_name_and_query()```
I mean, at face value, it returns None because you never return anything from the function. You are copying it to the clip board.
A bit more detail would be good. What functions were refactored? What is the output to the console of all your print statements?
As an aside, I'd recommend wrapping the module functionality (last two calls) in an if __name__ == "__main__" block

Mysql prepared statements not getting replaced with values in python

Have tried with both (?) and (%s) but doesn't seem to be working. Where am I gong wrong?
def update(phone,name):
conn = sqlite3.connect(db)
print ("\nOpened database for updates successfully")
sql = "UPDATE VARUN set PHONE = %s where NAME= %s "
print (sql)
conn.execute(sql,(phone,name))
'''
conn.execute("UPDATE VARUN set PHONE = (?) where NAME= (?) ",(phone,name));
'''
conn.commit()
----- calling function ----
contactlist[selection()]=[nameVar.get(), phoneVar.get()]
updt = (contactlist[selection()])
name = (updt[0])
phone = (updt[1])
print (name,phone)
try:
update(name,phone)
except:
tkinter.messagebox.showwarning("cannot be blank")
else:
setList ()
saveContact()
First of all, you are using a bare except clause which prevents you from seeing what errors are thrown from the function. Remove it and see how it fails.
And, you need to have ? placeholders without the surrounding parenthesis:
def update(phone, name):
conn = sqlite3.connect(db)
cursor = conn.cursor()
print ("\nOpened database for updates successfully")
sql = "UPDATE VARUN set PHONE = ? where NAME= ?"
cursor.execute(sql, (phone, name))
conn.commit()

Python cx_Oracle SQL with bind string variable

I have a problem with creating SQL query for Oracle database using Python.
I want to bind string variable and it does not work, could you tell me what am I doing wrong?
This is my code:
import cx_Oracle
dokList = []
def LoadDatabase():
conn = None
cursor = None
try:
conn = cx_Oracle.connect("login", "password", "localhost")
cursor = conn.cursor()
query = "SELECT * FROM DOCUMENT WHERE DOC = :param"
for doknumber in dokList:
cursor.execute(query, {'doknr':doknumber})
print(cursor.rowcount)
except cx_Oracle.DatabaseError as err:
print(err)
finally:
if cursor:
cursor.close()
if conn:
conn.close()
def CheckData():
with open('changedNamed.txt') as f:
lines = f.readlines()
for line in lines:
dokList.append(line)
CheckData()
LoadDatabase()
The output of cursor.rowcount is 0 but it should be number greater than 0.
You're using a dictionary ({'doknr' : doknumber}) for your parameter, so it's a named parameter - the :param needs to match the key name. Try this:
query = "SELECT * FROM DOCUMENT WHERE DOC = :doknr"
for doknumber in dokList:
cursor.execute(query, {'doknr':doknumber})
print(cursor.rowcount)
For future troubleshooting, to check whether your parameter is getting passed properly, you can also try changing your query to "select :param from dual".

Categories