Python mysql.connector 插入不起作用

Python mysql.connector insert does not work

我是第一次使用 Python mysql.connector,我无法创建有效的插入语句。

这是table:

'CREATE TABLE IF NOT EXISTS products (id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255));'

我正在尝试插入一个变量作为标题,而 ID 应该自动递增。我尝试了多种解决方案,但根本行不通。

def insert_product(title: str):
    insert_product_query = 'INSERT INTO products (title) VALUES (%s);'
    cursor.execute(insert_product_query, (title,))

这运行没有任何错误,但插入不工作。它什么都不做。我尝试了多个版本,带有“?”而不是“%s”并且没有元组,但它不会工作。

我尝试的另一个解决方案是:

def insert_product(title: str):
    insert_product_query = f'INSERT INTO products (title) VALUES (\'{title}\')'
    print(insert_product_query)
    cursor.execute(insert_product_query)

我打印了插入语句,当我将它直接复制粘贴到数据库中时,它工作得很好,所以我不知道为什么它不能在 python 代码中工作,因为它不是产生任何错误。

我发现了许多类似的问题,但 none 的解决方案对我有用。

我希望有人能帮助我,因为我可能会忽略一些显而易见的事情。

提前致谢!

Python 的连接器默认禁用自动提交(作为一个合理的库会做的!)。您需要在执行 DML 语句后显式提交:

con.commit() # Assuming con is the name of the connection variable