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

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.

Related

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

Insert into MySQL table with 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.

Python mysql.connector module, Passing data into string VALUES %s

I'm having trouble passing data into %s token. I've looked around and noticed that this Mysql module handles the %s token differently, and that it should be escaped for security reasons, my code is throwing this 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
If I do it like this:
sql_insert = ("INSERT INTO `Products` (title) VALUES(%s)"),(data)
I get a tuple error..
import mysql.connector
from mysql.connector import errorcode
cnx = mysql.connector.connect (user='userDB1', password='UserPwd1',
host='somedatabase.com', database='mydatabase1')
cursor = cnx.cursor()
sql_insert = ("INSERT INTO `Products` (title) VALUES(%s)")
data=('HelloSQLWORLD')
cursor.execute(sql_insert,data)
cnx.commit()
cnx.close()
No, don't do it the way #Jeon suggested - by using string formatting you are exposing your code to SQL injection attacks. Instead, properly parameterize the query:
query = """
INSERT INTO
Products
(title)
VALUES
(%s)"""
cursor.execute(query, ('HelloSQLWORLD', ))
Note how the query parameters are put into a tuple.
Pythonic string formatting is:
str1 = 'hello'
str2 = 'world'
'%s, %s' % (str1, str2)
Use % with tuple, not ,
For your particular case, try:
cursor.execute(sql_insert % (data))

pywhois parsed results into mysql

sorry if you consider as repost, quite simple code and i suspect also a trivial error here, but can't move forward:
import whois
import MySQLdb
db = MySQLdb.connect(host="localhost", user="root", passwd="pass", db="whois")
cur = db.cursor()
wi = whois.whois("google.com")
cur.execute("""INSERT INTO wrec (dname, wfull, dns) VALUES (%s, %s, %s)""") , (wi.domain_name, wi.text, wi.name_servers)
ends up in:
_mysql_exceptions.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 '%s, %s, %s)' at line 1")
as said, suspecting trivial error. any suggestions? thanks a lot in advance
You placed the fetched Whois variables outside the execute function!
Change:
cur.execute("""INSERT INTO wrec (dname, wfull, dns) VALUES (%s, %s, %s)""") , (wi.domain_name, wi.text, wi.name_servers)
To:
cur.execute("""INSERT INTO wrec (dname, wfull, dns) VALUES (%s, %s, %s)""", (wi.domain_name, wi.text, wi.name_servers))
Edit:
And don't forget to add:
db.commit()
at the end of the script.

SQL query using %s in Python 3.3

I'm trying to retrieve data from a MySQL-database.
A = "James"
query = ("SELECT * FROM DB.tblusers WHERE UserName = %s ")
c = mysql.connector.connect(user='root', password='',
host='127.0.0.1',
database='DB')
cur1 = c.cursor()
cur1.execute(query, A)
Gives the following error message:
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 '%' at line 1
But the SQL works in the mySQL Workbench.
Any ideas?
A should be a tuple, try with A = ("James",)
see documentation of MySQLCursor.execute(operation, params=None, multi=False)
EDIT: added a comma, thanks to "swordofpain" (I learned something)

Categories

Resources