在Python中不使用MySQL连接器插入记录

2024-10-03 11:19:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经搜索过了,无论我做什么尝试,我都无法将记录插入Python中的MySQL表中。我做了一个承诺,但仍然没有任何承诺。这是我现在拥有的代码。感谢您提供的任何见解

commentauthor = comment.author
theauthor = commentauthor.name

try:
    mydb = mysql.connector.connect(
        host="localhost",
        user="user",
        passwd="pass",
        database="mydb"
)

    readcursor = mydb.cursor(buffered=True)
    SQL = "SELECT * FROM atable WHERE username = '%s'" % (theauthor)
    readcursor.execute(SQL)
    if readcursor.rowcount == 0:
        repcount = 1
    else:
        myresult = readcursor.fetchone()
        for row in myresult:
            repcount = row[1] + 1

    writecursor = mydb.cursor()
    if repcount == 1:
        SQL = "INSERT INTO atable (username, usercount) VALUES ('%s', %d)" % (theauthor, repcount)
    else:
        SQL = "UPDATE atable SET usercount = %d WHERE username = '%s'" % (repcount, theauthor)

    writecursor.execute(SQL)
    mydb.commit

    print(SQL)

    SQL = "SELECT * FROM atable WHERE username = '%s'" % (theauthor)
    readcursor.execute(SQL)

    print(SQL)

    acount = readcursor.fetchone()[1]
    print(acount)

    readcursor.close
    writecursor.close
    mydb.close
except:
    print(SQL)
    print("Error: unable to fetch data")

插入之后,下一次完成的选择显示值为“1”(就像插入数据一样),但表中实际上没有数据。使用MySQL管理GUI,表是空的,第二次运行相同的代码不会返回任何记录


Tags: 代码closeexecutesql记录mysqlusernamewhere