MySQL + Python : Wrong number of arguments during string formatting - python

I am executing below query in python to insert data:
query = "INSERT INTO tweetMelbourne(created_at,geo_coordinates_latitude,geo_coordinates_longitude,user_id,polarity_score)" \
"VALUES(?,?,?,?,?)"
args = (created_at,geo_coordinates_latitude,geo_coordinates_longitude,user_id,polarity_score)
try:
cursor = conn.cursor()
cursor.execute(query, args)
But its giving error: Wrong number of arguments during string
formatting
My MySQL table is like this:
CREATE TABLE tweetMelbourne (
`created_at` DATETIME NOT NULL ,
`geo_coordinates_latitude` decimal(12,9) DEFAULT NULL,
`geo_coordinates_longitude` decimal(12,9) DEFAULT NULL,
`user_id` INT,
`polarity_score` INT
)DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Related

Issue while trying to select record in mysql using Python

Error Message
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' at line 1
MySQL Database Table
CREATE TABLE `tblorders` (
`order_id` int(11) NOT NULL,
`order_date` date NOT NULL,
`order_number` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `tblorders`
ADD PRIMARY KEY (`order_id`),
ADD UNIQUE KEY `order_number` (`order_number`);
ALTER TABLE `tblorders`
MODIFY `order_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
Code
mydb = mysql.connector.connect(host = "localhost", user = "root", password = "", database = "mydb")
mycursor = mydb.cursor()
sql = "Select order_id from tblorders where order_number=%s"
val = ("1221212")
mycursor.execute(sql, val)
Am I missing anything?
You must pass a list or a tuple as the arguments, but a tuple of a single value is just a scalar in parentheses.
Here are some workarounds to ensure that val is interpreted as a tuple or a list:
sql = "Select order_id from tblorders where order_number=%s"
val = ("1221212",)
mycursor.execute(sql, val)
sql = "Select order_id from tblorders where order_number=%s"
val = ["1221212"]
mycursor.execute(sql, val)
This is a thing about Python that I always find weird, but it makes a kind of sense.
In case you want to insert data you have to modify your SQL. Use INSERT instead of SELECT like this:
INSERT INTO tblorders (order_number) VALUES ("122121");
That statement will add new record to the table. Besides, in MariaDB you need to use ? instead of %s that works on Mysql database.
sql = "INSERT INTO tblorders (order_number) VALUES (?);"
val = "1231231"
mycursor.execute(sql, [val])

How to execute sql query with python variables null or empty

Hi I'm using python 3 and snowflake.
Example:
MY_SCHEMA = 'TEST'
MY_TABLE = Empty
sql = "SELECT SCHEMA, TABLE FROM TABLE_LOG WHERE SCHEMA = %s AND TABLE = %s"
tuple1 = (MY_SCHEMA, MY_TABLE)
cur.execute(sql,tuples1)
I tried with this:
WHERE SCHEMA = %s OR (SCHEMA IS NULL AND %s IS NULL) also WHERE SCHEMA = IIF(%S IS NULL, SCHEMA, %s)
I'm getting TypeError: not enough arguments for format string. I would like to run this query for all schemas if I dont have defined MY_SCHEMA variable and also for all tables if MY_TABLE variable is null or empty.
I would be grateful for any advice.
I found a solution this issue:
MY_SCHEMA = 'TEST'
MY_TABLE = None
cur.execute("SELECT SCHEMA,TABLE FROM TABLE_LOG WHERE SCHEMA = COALESCE(%(schema_variable)s,SCHEMA) AND TABLE = COALESCE(%(table_variable)s,TABLE )",{"schema_variable": MY_SCHEMA, "table_variable": MY_TABLE})

How to remove extra quotes in pymysql

This code uses pymysql, however when i try to insert the variable title into the sql query it comes out with 'title' for example when i set title to = test the database created is 'test' is there a way to create the table without the extra quotes
import pymysql
connection = pymysql.connect(
host='localhost',
user='root',
password='',
db='comments',
)
c= connection.cursor()
sql ='''CREATE TABLE IF NOT EXISTS `%s` (
`comment_id` int(11) NOT NULL,
`parent_comment_id` int(11) NOT NULL,
`comment` varchar(200) NOT NULL,
`comment_sender_name` varchar(40) NOT NULL,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8; '''
c.execute(sql, (title))
In my case I just rewrite the escape method in class 'pymysql.connections.Connection', which obviously adds "'" arround your string.
I don't know whether it is a bad idea, but there seems no better ways, if anyone knows, just let me know.
Here's my code:
from pymysql.connections import Connection, converters
class MyConnect(Connection):
def escape(self, obj, mapping=None):
"""Escape whatever value you pass to it.
Non-standard, for internal use; do not use this in your applications.
"""
if isinstance(obj, str):
return self.escape_string(obj) # by default, it is :return "'" + self.escape_string(obj) + "'"
if isinstance(obj, (bytes, bytearray)):
ret = self._quote_bytes(obj)
if self._binary_prefix:
ret = "_binary" + ret
return ret
return converters.escape_item(obj, self.charset, mapping=mapping)
config = {'host':'', 'user':'', ...}
conn = MyConnect(**config)
cur = conn.cursor()

Python MySQLDB - not all arguments converted during string formatting

When I execute my programme I have this error :
query = query % tuple([db.literal(item) for item in args])
TypeError: not all arguments converted during string formatting
I tried to fixe it but nothing worked. This is my code.
Thanks for your help.
con = mdb.connect('localhostt', '****', '*********', 'credentials');
with con:
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS Data")
cur.execute("CREATE TABLE Data(Id INT PRIMARY KEY AUTO_INCREMENT, \
Name VARCHAR(25))")
name1 = "Paste"
country_code = 'PSE'
district = 'Someyork'
population = 10008
cur.execute("INSERT INTO Data(Name) VALUES(%s) ",(name1))
con.comit()
You want
cur.execute("INSERT INTO Data(Name) VALUES(%s)", (name1,))
Notice the extra comma in (name1,) - it's needed to make it a tuple. Without the comma, it's the same as
cur.execute("INSERT INTO Data(Name) VALUES(%s)", name1)
and since strings are sequences too, the connector iterates over each char in name1, hence the error.

How to leave the unnecessary quotation marks when i convert a csv into a mysqldb with python?

I've got a CSV excel file, which one I want to convert into mysqldb.
It is working very fine, but in every cell in the MYSQLdb there are unnecessary quotation marks, like this: "".
When the cell is empty I see this: ""
When the cell is not empty is see this: "somethingdata"
I can't understand, why put these quotation marks when in the csv file there are none.
Here my code, I think it is correct too.
connection = MySQLdb.connect(host='localhost',
user='root',
passwd='1234',
db='database')
cursor = connection.cursor()
query = """
CREATE TABLE `test` (
`Megnevezes` varchar(100) DEFAULT NULL,
`2015` varchar(100) DEFAULT NULL,
`2014` varchar(100) DEFAULT NULL,
`2013` varchar(100) DEFAULT NULL,
`2012` varchar(100) DEFAULT NULL,
`2011` varchar(100) DEFAULT NULL,
`ID` int(10) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=32 DEFAULT CHARSET=utf8"""
cursor.execute(query)
connection.commit()
cursor.close()
connection = MySQLdb.connect(host='localhost',
user='root',
passwd='1234',
db='database')
cursor = connection.cursor()
query = """ load data local infile 'C:/Python27/output.csv'
into table test
character set latin1
fields terminated by ';'
lines terminated by '\n'
ignore 1 lines;
"""
cursor.execute(query)
connection.commit()
cursor.close()
Any ideas how can I fix this issue?
https://dev.mysql.com/doc/refman/5.7/en/load-data.html
Use the: ENCLOSED BY 'char' where char will be "

Categories