Python MySQL, get special column names - python

I am using Python to fetch MySQL process.
The codes are shown below:
import mysql.connector
mydb = mysql.connector.connect(
host='192.168.95.9', user='root',
passwd='qwe123', database='information_schema')
cursor = mydb.cursor()
sql = "SELECT CONCAT('KILL ',id,';') FROM information_schema.processlist
WHERE `TIME`>100 AND `COMMAND` = 'Sleep' AND `DB` IN ('api','monitor', 'workflow');"
cursor.execute(sql)
cursor.fetchall()
The sql shown above can get results but in python, it returns nothing. When I get rid of the where condition, it returns values as expected. I also tried
sql = "SELECT CONCAT('KILL ',id,';') FROM information_schema.processlist WHERE \`TIME\`>100 AND \`COMMAND\` = 'Sleep' AND \`DB\` IN ('api','monitor', 'workflow');"
But it returns error:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\`TIME\`>100 lim
How to address this issue?

Related

how to insert string into query in python pymysql

I have a following query:
cursor = connection.cursor()
query = """
SELECT *
FROM `my_database`.table_a
"""
result = cursor.execute(query)
which works as expected. But I need to change my_database in cursor.execute. I try:
cursor = connection.cursor()
query = """
SELECT *
FROM %s.table_a
"""
result = cursor.execute(query, ("my_database",))
which gives an error pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''my_database'.table_a at line 2")
how can I insert database name in cursor.execute please?
It is not possible to bind a database name (or any other database object name) using a placeholder in a prepared statement. This would be, among other problems, a security risk. However, you might be able to use an f-string here instead:
cursor = connection.cursor()
db_name = "my_database"
query = f"""
SELECT *
FROM {db_name}.table_a
"""
result = cursor.execute(query)
It should also be mentioned that the above is only SQL injection safe if you are certain that the database name is not coming from outside your own application.

Python-MySQL prepared statement error while selecting where a value IS NULL

I want to select rows where a value is null but I get this error on executing using Python-MySQL prepared statement.
mysql.connector.errors.InterfaceError: 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 '?' at line 1
import mysql.connector
connection = mysql.connector.connect(database="XXXXX", user="XXXXX", password="XXXXX", host="XXXXX")
cursor = connection.cursor(prepared=True)
parameters = ["Ahmed", None]
statement = "SELECT * FROM Persons WHERE name_first = ? AND start_date IS ?"
cursor.execute(statement, tuple(parameters))

1064 error while operating MySQL database with Python

I want to write a program in Python to control MySQL database, but the following error occurs
pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; chec
k the manual that corresponds to your MySQL server version for the right syntax
to use near 'Code,type, number,Whether )VALUES ('cl8k-k520-fg45-d4sa-sd9k','n' at line 1")
Codeļ¼š
import pymysql
db = pymysql.connect("localhost", "root", "root", "test")
cursor = db.cursor()
sql = "INSERT INTO BOOKS(Activation Code, \
type, number,Whether ) \
VALUES (%s,%s,%s,%s)"
data = [("cl8k-k520-fg45-d4sa-sd9k",'n','10','n'),
("jhg6-58jh-gh8o-8uik-7jk8",'c','20','n'),
("x5hg-gf5h-4hj5-g4h5-fh5t",'y','999','n'),
("fg8j-h584-fd4g-fg4d-fgg4",'n','1','y'),
("4jk4-5kl4-4klk-4lji-4ghj",'e','6','n'),
]
cursor.executemany(sql,data)
db.close()
This is my first time to ask questions on this platform. I hope to get answers
enclose Activation Code as 'Activation Code'

Can't execute a query with the right syntax using mysql.connector 8.0 in jupyter notebook

I'm trying to set up a small database for a simple card game using mysql.connector 8.0 in jupyter notebook, yet I can't execute any queries, it says that the syntax is wrong even though it's all good.
That's the code:
'''
import random
import collections
import mysql.connector
conn = mysql.connector.connect(
host='localhost',
user='root',
passwd='*****',
auth_plugin='mysql_native_password',
database='CardGame'
)
cur = conn.cursor()
query = "CREATE TABLE cards (id int PRIMARY KEY AUTO_INCREMENT,rank VARCHAR(1),suit VARCHAR(10))"
cur.execute(query)
conn.commit()
'''
That's the error I keep getting:
ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'rank VARCHAR(1), suit VARCHAR(10))' at line 1
I don't have an access to a MySQL database at the moment but your create table has RANK as a column name which is also a keyword. Can you change that to something else and try it out?

Values in mysql with python

I'm trying to do a little program for print an user that it was selected in a list. But I don't know how to mix a variable with a query. I tried this but I get an error:
def datos(name):
conn = MySQLConnection(host=DB_HOST,user=DB_USER,password=DB_PASS,database=DB_NAME)
cursor = conn.cursor()
cursor.execute("SELECT nombre FROM clientes WHERE nombre = %s", name)
Error:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s' at line 1

Categories