Insert into MySQL table with Python - python

I am trying to insert basic data into my MySQL table without any success yet I'm using basic tutorials as demos.
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
My MySQL
CREATE TABLE awesome (
id int NOT NULL AUTO_INCREMENT,
test varchar(50),
PRIMARY KEY (id)
);
My Python code
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="pass",
database="db"
)
mycursor = mydb.cursor()
sql = "INSERT INTO awesome (test) VALUES (%s)"
val = ("Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")

Yes the problem arises when there is only 1 argument in val tuple. Use
val=("Highway 21",)
Note the comma at the end.

Related

Python tkinter--ProgrammingError: 1064 (42000)

Following code is a function design for update data in mysql database.I get issue with following error message:
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 '#gmail.com,gender=Female,
def update_data(self):
con = mysql.connector.connect(
host="localhost",
user="root",
password="123456",
database="stm",
)
cur = con.cursor()
cur.execute(
"""
update
students
set
name=%s,
email=%s,
gender=%s,
contact=%s,
dob=%s,
address=%s,
where
roll_no=%s;
""" % (
self.name_var.get(),
self.email_var.get(),
self.gender_var.get(),
self.contact_var.get(),
self.dob_var.get(),
self.txt_Address.get('1.0', END),
self.Roll_No_var.get(),
), )
con.commit()
con.close()
self.fetch_data()
self.clear()

ProgrammingError 1064 doing CREATE TABLE AS SELECT from an existing table with MySQL in Python

I have an existing table in the cloud and I want to make a copy of it. I connect to my database via pymysql, extract the username from an input provided from the new user, and I want to create a new table that will be called by the username, and that table will be a copy of the original one. When I run the code below, I have the following 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 ''username' AS SELECT * FROM original_table' at line 1")
uname = blabla#bla.com
conn = pymysql.connect(
host="db.host",
port=int(3306),
user=user,
passwd=password,
db=db,
charset='utf8mb4'
)
cur = conn.cursor()
table_name = uname.replace('#', '_').replace('.', '_')
print('TABLE NAME:', table_name)
cur.execute(""" CREATE TABLE %s AS SELECT * FROM original_table """, (table_name))
Parameter quoting is for quoting values. Quoting table names does not work, because in MySQL the way to quote a table name is by using backticks (`), not quotation marks.
MariaDB [test]> CREATE TABLE 'username' AS SELECT * FROM my_table;
ERROR 1064 (42000): 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 ''username' AS SELECT * FROM my_table' at line 1
In this cause you need to use string formatting to create the SQL statement (you can use backticks to defend against SQL-injection*):
cur.execute(""" CREATE TABLE `%s` AS SELECT * FROM original_table """ % table_name)
* I'm not an expert on SQL-injection, so do some research if table_name originates outside your application.

SQL truncate table where table name is defined in function argument or variable

I'm trying to pass variable or function argument to the execute method
import pymysql
tablename = 'test_table'
con = pymysql.connect(**...)
with con.cursor() as cur:
cur.execute("TRUNCATE TABLE %s", tablename)
con.commit()
con.close()
Following error:
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 ''test_table'' at line 1")
Expecting to see no errors and the test_table empty of rows.
SO is slacking lately...
I did this instead and it worked:
import pymysql
tablename = 'test_table'
con = pymysql.connect(**...)
with con.cursor() as cur:
cur.execute("TRUNCATE TABLE %s" % tablename)
con.commit()
con.close()
print('Done')

Accessing MySQL from Python 2.7: ProgrammingError: 1045 (28000)

I am having difficulties connecting to a MySQL database using Python 2.7. The error I'm getting is
ProgrammingError: 1045 (28000): Access denied for user
'tommyan'#'localhost' (using password: YES)
I know similar questions exist, but none of those were helpful to me. My code is below, thanks in advance.
import mysql.connector
mydb = mysql.connector.connect(
host="127.0.0.1",
user="tommyan",
passwd="######",
database="mydatabase"
)
mycursor = mbdb.cursor()
sql = "INSERT INTO places (name, desc) VALUES (%s, %s)"
val = ("Natinal gallery", "Housing masterpieces by painters including van Gogh,
Renoir, da Vinci and Michelangelo")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")

How to intsert quotation mark `'` into mariaDB using mysql-client?

I am using mariaDB(Ver 15.1 Distrib 10.0.17-MariaDB, for osx10.10 (x86_64)) and mysqlclient==1.3.6.
I just want to insert a string into a varcharfield.
import MySQLdb
import json
conn = MySQLdb.connect(
host='localhost',
port=3306,
user='root',
passwd='',
db='ng')
cur = conn.cursor()
cur.execute(INSERT INTO `current_table` (`id`, `name`) VALUES (NULL, '{name}');".format(name="Lily' dog"))
conn.commit()
but I always got a error like this:
_mysql_exceptions.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 's dog', NULL)' at line 1")
what should I do if I want to insert quotation mark by mysql-client?
According to Amadan's comment, in bobby-tables(the site for preventing SQL injections), it suggest:
Using the Python DB API, don't do this:
Do NOT do it this way:
cmd = "update people set name='%s' where id='%s'" % (name, id)
curs.execute(cmd)
Instead, do this:
cmd = "update people set name=%s where id=%s"
curs.execute(cmd, (name, id))
so in my situation, just modify the execute line to :
cmd = "INSERT INTO `current_table` (`id`, `name`) VALUES (NULL, %s);"
cur.execute(cmd, ("Lily's dog"))
and this can avoid the error which quotation mark leads to.

Categories

Resources