Python insert variable to mysql via mysql.connector - python

I am trying to create one python script to insert data into mysql, but I got an error when I try to test it.
This is how I create the table:
CREATE TABLE aaa (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
data CHAR(30) NOT NULL,
PRIMARY KEY (id)
);
This is my python script:
import mysql.connector
from time import strftime, gmtime, sleep
cnx = mysql.connector.connect(
user='root', password='abcd', database='test_db'
)
cur = cnx.cursor()
# get current timestamp
curr_time = strftime("%Y%m%d_%H%M%S", gmtime())
cur.execute(
"INSERT INTO aaa(data) VALUES (%s)", (curr_time)
)
cnx.commit()
cnx.close()
The error is like this:
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
Can anyone help me solve this problem?

replace , with % in "INSERT INTO aaa(data) VALUES (%s)", (curr_time) it should be "INSERT INTO aaa(data) VALUES (%s)"%(curr_time).
#tsh is correct use this (curr_time) -> (curr_time,) instead

Related

Python MySQL, get special column names

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?

MySQL Python creating table with variable as name

I am working on a project with a friend and am new to sql databases. I want to have a database with tables named after the date they were created. I have tried multiple things but i thought .format() would be the best, but it didnt work. This is how it currently looks:
today = date.today()
d1 = today.strftime("%b-%d-%Y")
sql = "CREATE TABLE {table} (CEO VARCHAR(255), profits INTEGER(10))"
mycursor.execute(sql.format(table = d1))
i am also trying to insert into the database with .format:
sql = "INSERT INTO{table} (CEO, profits) values (%s, %s)"
mycursor.execute(sql.format(table = d1), (Company(c).get_CEO(), int(Company(c).get_profit())))
mydb.commit()
I get the error:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax;
You have no space between INTO and {table}

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?

Mysql connector Python Syntax error

I want to run the create function in a tkinter interface but it give me this error:
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 ''' (id INT NOT NULL AUTO_INCREMENT,cash INT,dt DATE, PRIMARY
KEY(id))' at line 1
This is the code. I have tried a lot of thinks but nothing...
from mysql.connector import MySQLConnection, Error
from tkinter import *
DB_HOST = 'localhost'
DB_USER = 'root'
DB_PASS = 'mysql123'
DB_NAME = 'Savings'
def create(Name):
try:
connection = MySQLConnection(host=DB_HOST,user=DB_USER,password=DB_PASS,database=DB_NAME)
cursor = connection.cursor()
tabla = Name.get()
cursor.execute("CREATE TABLE %s (id INT NOT NULL AUTO_INCREMENT,cash INT,dt DATE, PRIMARY KEY(id))", (tabla,))
print("Hecho!")
except Error as e:
print(e)
finally:
connection.commit()
cursor.close()
connection.close()
You cannot parameterize table or column names. Use string formatting (but make sure you trust your source or validate the input table name carefully):
cursor.execute("CREATE TABLE {table} (id INT NOT NULL AUTO_INCREMENT,cash INT,dt DATE, PRIMARY KEY(id))".format(table=tabla))
Note that you can use the mysql connector to escape strings:
tabla = connection.converter.escape(tabla)

Can't execute an INSERT statement in a Python script via MySQLdb

I'm trying to execute a basic INSERT statement on a MySQL table from a Python script using MySQLdb. My table looks like this:
CREATE TABLE `testtable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`testfield` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
Running this query from the MySQL command line works fine:
INSERT INTO `testtable` (`id`, `testfield`) VALUES (NULL, 'testvalue');
But when I try to execute the query from a Python script, no rows get inserted. Here's my code:
conn = MySQLdb.connect(host=db_host, port=db_port, user=db_user, passwd=db_password, db=db_database)
cursor = conn.cursor ()
cursor.execute ("INSERT INTO `testtable` (`id`, `testfield`) VALUES (NULL, 'testvalue')")
print "Number of rows inserted: %d" % cursor.rowcount
cursor.close()
conn.close()
Oddly, this will print "Number of rows inserted: 1." I can also confirm that this query increments the ID field, because when I add another row via the command line, the value of its ID is the same as if the Python script had successfully inserted its rows. However, running a SELECT query returns none of the rows from the script.
Any idea what's going wrong?
You either need to set conn.autocommit(), or you need to do conn.commit() - see the FAQ
you need to commit:
conn.commit()
http://mysql-python.sourceforge.net/FAQ.html#my-data-disappeared-or-won-t-go-away

Categories