Python MySQLDB - not all arguments converted during string formatting - python

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.

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

Parameterized Table Population

I am trying to populate a table(whose name is parameterized). The program runs fine, up until the point where the command gets executed.
Here is the code:
table_name = input("Enter table name: ")
value_name = input("Enter name: ")
sql = "INSERT INTO %s (name) VALUES (%s)" % db.escape_string(table_name), (value_name)
cursor.execute(sql)
I get the following error:
TypeError: not enough arguments for format string
Thanks to anyone who takes the time to help. Have a great rest of the day :)
as an alternative you good go with the new formatting format
sql = f"INSERT INTO {tab} (name) VALUES ({val})".format(tab=db.escape_string(table_name),
val=value_name)
or
sql = f"INSERT INTO {db.escape_string(table_name)} (name) VALUES ({value_name})"
Just wrap the sql formatting like below and try.
sql = "INSERT INTO %s (name) VALUES (%s)" % (db.escape_string(table_name), value_name)

Error: 1210: Incorrect number of arguments executing prepared statement

I'm trying to insert data into MySQL using Python.
What is the cause of this error?
ProgrammingError: 1210: Incorrect number of arguments executing
prepared statement
My python codes:
connection = mysql.connector.connect(host='localhost',
database='popsww2017',
user='root',
password='')
records_to_insert = [('---2q7vcZGU', 'Partner-provided', '35', '9s1Pvm0U8Gg8mRavZhVXdg', 'A663893851990558', '1066/2016/HDHT-Pops-Kha Ly', '1467', '0.100598')]
sql_insert_query = "INSERT INTO raw_music (`Video_ID`, `Content_Type`, `Video_Duration`, `Channel_ID`, `Asset_ID`, `Asset_Labels`, `Owned_Views`, `Partner_Revenue`) VALUES ( '%s', '%s' , '%s' , '%s', '%s' , '%s' , '%s' , '%s') "
cursor = connection.cursor(prepared=True)
result = cursor.executemany(sql_insert_query,records_to_insert)
connection.commit()
My tables:
Video_ID varchar(50) utf8_unicode_ci
Content_Type varchar(100) utf16_unicode_ci
Video_Duration int(11)
Channel_ID varchar(100) utf8_unicode_ci
Asset_ID varchar(50) utf32_unicode_ci
Asset_Labels varchar(400) utf32_unicode_ci
Owned_Views int(20)
Partner_Revenue float
the secret to make it work it's to add a comma at the end of the single valued tuple.
Example:
# a tuple
to_insert = ('A value to insert'**,**)
In this case:
records_to_insert = [('---2q7vcZGU', 'Partner-provided', 35, '9s1Pvm0U8Gg8mRavZhVXdg', 'A663893851990558', '1066/2016/HDHT-Pops-Kha Ly', 1467, 0.100598)**,**]
It works for single valued tuples.
I hope it helps!
You forgot to pass the executemany method parameters:
result = cursor.executemany(sql_insert_query,records_to_insert)
MySQLCursor.executemany() Method
Syntax:
cursor.executemany(operation, seq_of_params)
This method prepares a database operation (query or command) and executes it against all parameter sequences or mappings found in the sequence seq_of_params.
Also your syntax is wrong (remove quotes), use the following instead:
records_to_insert = [('---2q7vcZGU', 'Partner-provided', '35', '9s1Pvm0U8Gg8mRavZhVXdg', 'A663893851990558', '1066/2016/HDHT-Pops-Kha Ly', '1467', '0.100598')]
sql_insert_query = "INSERT INTO raw_music (`Video_ID`, `Content_Type`, `Video_Duration`, `Channel_ID`, `Asset_ID`, `Asset_Labels`, `Owned_Views`, `Partner_Revenue`) VALUES ( %s, %s , %s , %s, %s , %s , %s , %s) "
cursor = connection.cursor(prepared=True)
result = cursor.executemany(sql_insert_query, records_to_insert)
executemany function is used when you need to insert many rows in the database. And the second parameter should be a list containing values to be inserted in these different rows. So either you modify the code to the following:
(Note that I have added square brackets [] to records_to_insert, making it a list)
records_to_insert = [('---2q7vcZGU', 'Partner-provided', 35, '9s1Pvm0U8Gg8mRavZhVXdg', 'A663893851990558', '1066/2016/HDHT-Pops-Kha Ly', 1467, 0.100598)]
sql_insert_query = "INSERT INTO raw_music (`Video_ID`, `Content_Type`, `Video_Duration`, `Channel_ID`, `Asset_ID`, `Asset_Labels`, `Owned_Views`, `Partner_Revenue`) VALUES ( '%s', '%s' , %d , '%s', '%s' , '%s' , %d , %f) "
cursor = connection.cursor(prepared=True)
result = cursor.executemany(sql_insert_query, records_to_insert)
connection.commit()

How to get columns from a query in python?

I have that query in a python program:
And i should create a multidimensional array (if it possible) or four arrays from this query for every column from the query.
Can you suggest an elegant way to solve it?
conn = #connection to the server
cursor=conn.cursor()
query = (" select id, name, phone, city from guest")
cursor.execute(query)
results = cursor.fetchall
for i in results:
print i
cursor.close()
conn.close()
Not elegant but it may assist to unravel the mysterious Python Connector Cursor Class and transfers the list of tuples (see Copperfield comment) with the data from the query, into a list (phoneList) of dictionaries (entries) with details of each entry in the database, that might be easier to work with in your python script:
# ref: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor.html
import mysql.connector
db = 'test'
table = 'phonebook'
phoneList = []
drop_table = ("DROP TABLE IF EXISTS {};").format(table)
# By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record.
# To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement:
# ALTER TABLE phonebook AUTO_INCREMENT=100;
create_table = ("CREATE TABLE {} ("
"id int NOT NULL AUTO_INCREMENT,"
"name varchar(30) NOT NULL,"
"phone varchar(30) NOT NULL,"
"city varchar(30) NOT NULL,"
"PRIMARY KEY (id))"
" ENGINE=InnoDB DEFAULT CHARSET=latin1;").format(table)
Names = {'Bill':{'phone':'55123123','city':'Melbourne'},
'Mary':{'phone':'77111123','city':'Sydney'},
'Sue':{'phone':'55888123','city':'Melbourne'},
'Harry':{'phone':'77777123','city':'Sydney'},
'Fred':{'phone':'88123444','city':'Yongala'},
'Peter':{'phone':'55999123','city':'Melbourne'}}
cnx = mysql.connector.connect(user='mysqluser', password='xxxx',host='127.0.0.1',database=db)
cursor = cnx.cursor(dictionary=True) # key to using **row format
cursor.execute(drop_table)
cursor.execute(create_table)
# populate db
for name,detail in dict.items(Names):
sql = ("INSERT INTO {} (name,phone,city) VALUES ('{}','{}','{}')".format(table,name,detail['phone'],detail['city']))
cursor.execute(sql)
sql = ("SELECT id,name,phone,city FROM {}".format(table))
cursor.execute(sql)
for row in cursor:
print("{id} {name} {phone} {city}".format(**row))
phoneList.append(row)
print phoneList[0]['name'],phoneList[0]['city']
print phoneList[3]['name'],phoneList[3]['phone']
for entries in phoneList: # list of dictionaries
print entries['name'],entries
for entries in phoneList:
for k,v in dict.items(entries):
print k,v
print "\n"
cnx.close()

MySQL + Python : Wrong number of arguments during string formatting

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;

Categories