TypeError: not enough arguments for format string python pymysql (Delete row)

Asked
Active3 hr before
Viewed126 times

8 Answers

pymysqlenoughtypeerrorpythonargumentsformat
90%

Python TypeError: not enough arguments for format string Solution,The “TypeError: not enough arguments for format string” error is raised when the number of arguments specified in a string format operation is not equal to the number of values you want to add into a string,,Python strings must be formatted using the correct number of arguments

Example_snippet/controller/utility/_pymysql.js/ students = ["Andy", "Malcolm",. . .
students = ["Andy", "Malcolm", "Lindsay", "Lucy"]
load more v
88%

I believe there's some unexpected behavior that happens when using the Database,execute_sql command with an SQL statement but no parameters

Example_snippet/controller/utility/_pymysql.js/ sql = "INSERT INTO some_table . . .
sql = "INSERT INTO some_table (column_a, column_b) VALUES ('hello_my_name_is_inigo', 'odd_%_percent')
database.execute_sql(sql) # or database.execute_sql(sql, params = None)
load more v
72%

I'm wondering why I would be getting a TypeError when in my code below and what arguments exactly I'm missing?,I'm doing the old 99 bottles song and trying to do it using a While loop, to help me continue to better learn that loop type, ,I've tried using parenthesis around the "bottles, s1" after the %, but still doesn't help

Example_snippet/controller/utility/_pymysql.js/ # Get number of beers bottles . . .
# Get number of beers
bottles = int(raw_input("How many bottles of beer? "))

#
return invalid response
if bottles < 1:
   print "That's not a good number"

if bottles == 1:
   s1 = "bottle"
s2 = "bottles"

elif bottles == 2:
   s1 = "bottles"
s2 = "bottles"

# sing verses
while bottles > 0:
   print "%d %s of beer on the wall," % bottles, s1
print "%d %s of beer." % bottles, s1
print "You take one down, pass it around,"
print "%d %s of beer on the wall." % (bottles - 1), s2
print
bottles -= 1
Step 2 continued with Traceback (most recent call la. . .
Traceback (most recent call last):
File "beer.py", line 47, in <module>
   print "%d %s of beer on the wall," % bottles, s1
   TypeError: not enough arguments for format string
load more v
65%

2Why after disk scan lost the path in the Path environment variable?,Find more questions by tags Python

Example_snippet/controller/utility/_pymysql.js/ sql = "insert into items (`res. . .
sql = "insert into items (`resource_id is`,`item_link`,`item_title`,`item_datetime`,`item_text_content`) values (%s,%s,%s,%s,%s)"
cursor.execute(sql, (str(resource_id is), (str(item_link), str(item_title), str(item_datetime), str(item_content))))
Step 2 continued with Traceback (most recent call la. . .
Traceback (most recent call last):
File "C:/PycharmProjects/parser_goose_and_boilerpipe.py", line 83, in <module>
   call_all_func(resources)
   File "C:/PycharmProjects/parser_goose_and_boilerpipe.py", line 79, in call_all_func
   cursor.execute(sql, (str(resource_id is), (str(item_link), str(item_title), str(item_datetime), str(item_content))))
   File "C:AppData\Local\Programs\Python\Python37-32\lib\site-packages\pymysql\cursors.py", line 168, in execute
   query = self.mogrify(query, args)
   File "AppData\Local\Programs\Python\Python37-32\lib\site-packages\pymysql\cursors.py", line 147, in mogrify
   query = query % self._escape_args(args, conn)
   TypeError: not enough arguments for format string

   Process finished with exit code 1
Step 3 continued with sql = "insert into items (`ite. . .
sql = "insert into items (`item_link`,`item_title`,`item_datetime`,`item_text_content`) values (%s,%s,%s,%s)"
cursor.execute(sql, (str(item_link), str(item_title), str(item_datetime), str(item_content)))
Step 4 continued with sql = "insert into items (`res. . .
sql = "insert into items (`resource_id is`,`item_link`,`item_title`,`item_datetime`,`item_text_content`) values (%s,%s)"
cursor.execute(sql, (str(resource_id is), (str(item_link), str(item_title), str(item_datetime), str(item_content))))
Step 5 continued with Traceback (most recent call la. . .
Traceback (most recent call last):
File "C:PycharmProjects/parser_russian_resource/parser_goose_and_boilerpipe.py", line 83, in <module>
   call_all_func(resources)
   File "C:PycharmProjects/parser_russian_resource/parser_goose_and_boilerpipe.py", line 79, in call_all_func
   cursor.execute(sql, (str(resource_id is), (str(item_link), str(item_title), str(item_datetime), str(item_content))))
   File "C:AppData\Local\Programs\Python\Python37-32\lib\site-packages\pymysql\cursors.py", line 170, in execute
   result = self._query(query)
   File "C:AppData\Local\Programs\Python\Python37-32\lib\site-packages\pymysql\cursors.py", line 328, in _query
   conn.query(q)
   File "C:AppData\Local\Programs\Python\Python37-32\lib\site-packages\pymysql\connections.py", line 517, in query
   self._affected_rows = self._read_query_result(unbuffered=unbuffered)
   File "C:AppData\Local\Programs\Python\Python37-32\lib\site-packages\pymysql\connections.py", line 732, in _read_query_result
   result.read()
   File "C:AppData\Local\Programs\Python\Python37-32\lib\site-packages\pymysql\connections.py", line 1075, in read
   first_packet = self.connection._read_packet()
   File "C:AppData\Local\Programs\Python\Python37-32\lib\site-packages\pymysql\connections.py", line 684, in _read_packet
   packet.check_error()
   File "C:AppData\Local\Programs\Python\Python37-32\lib\site-packages\pymysql\protocol.py", line 220, in check_error
   err.raise_mysql_exception(self._data)
   File "C:AppData\Local\Programs\Python\Python37-32\lib\site-packages\pymysql\err.py", line 109, in raise_mysql_exception
   raise errorclass(errno, errval)
   pymysql.err.InternalError: (1136, "Column count doesn't match value count at row 1")

   Process finished with exit code 1
load more v
75%

Here is the last couple of lines in the error:,You can unpack the data using *, This replaces data (a list of objects) with the objects themselves so you will be properly sending a bunch of arguments instead of one single list as the argument, like,What am I doing wrong? It has to be in the execute function --> cursor

Example_snippet/controller/utility/_pymysql.js/ File "C:\Users\kathy\PycharmPr. . .
File "C:\Users\kathy\PycharmProjects\kathy\databaseLogic.py", line 142, in update_record
cursor.execute(update_query, (data, vector_to_update))
File "C:\Users\kathy\PycharmProjects\kathy\venv\lib\site-packages\pymysql\cursors.py", line 168, in execute
query = self.mogrify(query, args)
File "C:\Users\kathy\PycharmProjects\kathy\venv\lib\site-packages\pymysql\cursors.py", line 147, in mogrify
query = query % self._escape_args(args, conn)
TypeError: not enough arguments
for format string
Step 2 continued with # this function updates the re. . .
# this
function updates the record chosen by the user
def update_record(vector_to_update):
   logging.debug("Executing: update_record")
try:
with mydb.cursor() as cursor:
   # prepared statement to update a record in the database
update_query = ('UPDATE myTable SET ref_date = %s, geo = %s, sex = %s, age_group = %s, '
   'student_response = %s, uom = %s, uom_id = %s, scalar_factor = %s, scalar_id = %s, '
   'vector = %s, coordinate = %s, value_field = %s, decimals = %s WHERE vector = "%s"')
# calls on the user_input
function in the dataModel file and stores input in "data"
data = dataModel.user_input()
# execute the query using the vector_to_update in the query
cursor.execute(update_query, (data, vector_to_update))
# commit changes to database
mydb.commit()
print('Updating data for vector: {}'.format(vector_to_update))
cursor.close()

except pymysql.DatabaseError as error:
   #
if no connection to database
print("Update record failed to execute {}".format(error))
# tells the user the input is invalid and goes back thru the delete_record
function
menu_update_record()
Step 3 continued with # this function is run from th. . .
# this
function is run from the mainMenuView
def menu_update_record():
   while True:
   # ask which row the user wants to update and store in a variable
vector_to_update = pyip.inputRegex(r 'v[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]',
   prompt = "Please enter the Vector # of the record you wish to update: ")
print()
# calls update_record
function from databaseLogic module
databaseLogic.update_record(vector_to_update)
# asks user
if they want to update another record
answer = input("Do you wish to update another record?: ").lower()
#
if yes, loops back thru the update_record
function
if answer == "y":
   databaseLogic.update_record(vector_to_update)
#
if no, returns to the main menu
elif answer == "n":
   # print student name
databaseLogic.student_name()
#
return to main menu
main()
#
if user enters anything
else
else :
   # tells the user to enter either y or n
print("Your entry in invalid. Please choose [y/n]: ")
load more v
40%

I've printed the output of my "payload" which I want to save to the MySQL database:,# is only used to indicate a comment when used inside Python code, In your query, it is inside the query string, and so is not parsed as a comment identifier, but as part of the query

Example_snippet/controller/utility/_enough.js/ ('B01MTOV8IP', '40462', '23.95. . .
('B01MTOV8IP', '40462', '23.95', 'n/a', 'Usually ships in 24 hours',
   'https://www.amazon.com/reviews/iframe?akid=AKIAIDCPAFSAQICDTFNQ&alinkCode=xm2&asin=B01MTOV8IP&atag=reakenture-20&exp=2017-08-25T17%3A27%3A37Z&v=2&sig=3zbBXVo4cQAJueFeVeo%252F%252FejvaUOmvuwAtfB4EfMyDiU%253D', 'CHG-GSTWL')
load more v
22%

Next story How to implement CountDownTimer reducing time functionality in Android

Example_snippet/controller/utility/_enough.js/ sql = "DELETE FROM %s WHER. . .
    sql = "DELETE FROM %s WHERE %s < NOW() - INTERVAL %s YEAR"
    delete_list = [{
       'TABLE_NM': 'tb_smplng_need_samp_siz_inq',
       'COLUMN_NM': 'CRTE_DT',
       'YEAR': 3
    }]
    cursor.executemany(sql, delete_list)
    connection.commit()
load more v
60%

Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers ,Thanks for contributing an answer to Stack Overflow!,Making statements based on opinion; back them up with references or personal experience,,Find centralized, trusted content and collaborate around the technologies you use most

Example_snippet/controller/utility/_enough.js/ sql = "DELETE FROM tb_user WHE. . .
sql = "DELETE FROM tb_user WHERE CRTE_DT < NOW() - INTERVAL %s YEAR"
delete_list = [3]
cursor.executemany(sql, delete_list)
connection.commit()