【问题标题】:pymysql error: 'str' object has no attribute 'nextset'pymysql 错误:“str”对象没有属性“nextset”
【发布时间】:2019-03-30 08:15:31
【问题描述】:

我在为自己构建一个随机项目时遇到了问题。我正在尝试将条目记录到用户输入的mysql 数据库中。我将它们存储在字典中。错误信息是

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

我已经用谷歌搜索过这个问题,但我只发现了类似的问题,但不是同样的错误。

mysql db 中的表头与字典键匹配。我确实意识到我在选择 (2) 时遇到了问题,但我的错误和我现在正在解决的问题只是当我选择选项 (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':

我得到的错误是:

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

有什么建议吗?

【问题讨论】:

  • 请正确缩进您的代码并添加完整的错误堆栈跟踪
  • 如果用户可以粘贴代码而不会弄乱缩进,那就太棒了!
  • @YepramYeransian 这确实是可能的。而且很容易。

标签: python mysql python-3.x


【解决方案1】:

我怀疑您可能源于使用dict 来保存.execute() 的参数,而不是在SQL 语句中使用命名字符串模式。

docs 建议在传递列表或元组时使用%s,而在传递dict 时使用%(name)s

我建议你试试这个代码:

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)

这也将确保列名和占位符的顺序相同。您的原始代码没有考虑到这一点(请记住,多次迭代 dicts 并不保证每次都给出相同的顺序)。


我完全忽略了您与数据库建立连接的部分。您需要将该连接作为参数传递给new_entry() 并使用它。

试试这个:

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, ...)

【讨论】:

  • 对于 Cursors.execute,“args”将是什么,因为它不再是“myDict”?类似 Cursor.execute(sql, args)
  • 我的旧版本是 pymysql.cursors.Cursor.execute(sql, myDict)
  • 我认为是 myDict.values(),
  • 不是这样,只是给出了同样的错误,但我可以尝试从这里构建,谢谢
  • @YepramYeransian 不,.execute() 行可以与这些更改保持不变。我将其添加到我的答案中。
猜你喜欢
  • 2018-02-08
  • 2016-04-07
  • 2021-07-19
  • 1970-01-01
  • 2018-03-15
  • 2016-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多