简体   繁体   中英

pymysql error: 'str' object has no attribute 'nextset'

I am running into an issue building a random project for myself. I am trying to record entries into a mysql database that the user types in. I am storing them in a dictionary. The error message is

  while self.nextset():
AttributeError: 'str' object has no attribute 'nextset'

I have googled and searched for this issue, but I only find issues kind of like it but not the same error.

My table headers in mysql db match the dictionary keys. I do realize I have issues with selection (2) but my error and what I am troubleshooting now is just when I select option (1).

import mysql
import pymysql
from datetime import date, datetime, timedelta

cursor = pymysql.cursors.Cursor

# Function for adding a new entry
def new_entry(name, date, task, time, notes):
    # Build dictionary with new entry information

    myDict = {
        'Employee': name,     # Name of employee
        'Date': date,         # Date of worked task
        'Task': task,   # Title of Task
        'Time': time,         # Time spent on task
        'Notes': notes   # Notes on the task
    }
    table = ('timesheet')
    placeholders = ', '.join(['%s'] * len(myDict))
    columns = ', '.join(myDict.keys())
    sql = "INSERT INTO %s ( %s ) VALUES ( %s )" % (table, columns, 
        placeholders)
    pymysql.cursors.Cursor.execute(sql, myDict)

#list all entries for a particular employee
def previous_entries(emp_name):
    pymysql.cursors.Cursor.execute(
        "SELECT * from user_data WHERE Name = %s", (emp_name,))

#list all entries that match a date or search term
#def search_entries():
#    return null

#Print a report of this information to the screen, including the date, title 
#of task, time spent, employee, and general notes.

if __name__ == '__main__':
    #cnx = mysql.connect(user='root', database='me10_mig')
    cnx = pymysql.connect(user='root', password='password', 
        database='me10_mig')

    print("Please enter (1), (2), or (3)")
    begin = input("Would you like to (1) enter a new entry or (2) display 
    all 
    previous entries or (3) display entries that match a date or search 
    term? ")

    if begin == '1':
        name = input("Your Name: ")
        date = input("Date of Time Worked: ")
        task = input("Title of Task: ")
        time = input("Time Spent on Task: ")
        notes = input("Notes on Time Worked: ")
        new_entry(name, date, task, time, notes)

    if begin == '2':
        name = input("What is the employee name: ")
        previous_entries(name)

    #if begin == '3':

The error I get says:

Traceback (most recent call last):
  File "C:/Users/a089673/Desktop/Python/TeamTreeHouse/Part 4/timesheet.py", line 61, in <module>
    new_entry(name, date, task, time, notes)
  File "C:/Users/a089673/Desktop/Python/TeamTreeHouse/Part 4/timesheet.py", line 27, in new_entry
    pymysql.cursors.Cursor.execute(sql, myDict)
  File "C:\Users\a089673\AppData\Roaming\Python\Python36\site packages\pymysql\cursors.py", line 165, in execute
    while self.nextset():
AttributeError: 'str' object has no attribute 'nextset'

Process finished with exit code 1

Any suggestions?

I suspect your might stem from using a dict to hold the arguments to .execute() , but not using named string patterns in the SQL statement.

The docs suggest using %s when passing a list or tuple, but rather use %(name)s when passing a dict .

I suggest you try this code:

def new_entry(name, date, task, time, notes):
    # Build dictionary with new entry information

    myDict = {
        'Employee': name,     # Name of employee
        'Date': date,         # Date of worked task
        'Task': task,   # Title of Task
        'Time': time,         # Time spent on task
        'Notes': notes   # Notes on the task
    }
    table = ('timesheet')

    column_list = []
    placeholder_list = []
    for k in myDict:
        column_list.append(k)
        placeholder_list.append('%(' + k + ')s')

    sql = "INSERT INTO %s ( %s ) VALUES ( %s )" % (
        table,
        ', '.join(column_list),
        ', '.join(placeholder_list))

    pymysql.cursors.Cursor.execute(sql, myDict)

This will also ensure that the column names and the placeholders are in the same order. Your original code did not consider that (remember, iterating over dicts multimple time is not garanteed to give the same order each time).


I totally overlooked the part where you establish a connection to the database. You need to pass that connection as a parameter to new_entry() and use it.

Try this:

def new_entry(cnx, name, date, task, time, notes):
    sql = "INSERT INTO timesheet (Employee, Date, Task, Time, Notes) VALUES (%s, %s, %s, %s, %s)"
    values = (name, date, task, time, notes)

    with cnx.cursor() as cursor:
        cursor.execute(sql, values)

cnx = pymysql.connect(user='root', password='password', database='me10_mig')
new_entry(cnx, ...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM