MySQLdb占位符实现不起作用

米沙瓦契奇

Python的MySQLdb模块应在SQL语句字符串中使用格式说明符实现占位符。我正在从MYSQL CookBook中举一个例子

import sys
import MySQLdb
import Cookbook

try:
    conn = Cookbook.connect ()
    print("Connected")
except MySQLdb.Error as e:
    print("Cannot connect to server")
    print("Error code:", e.args[0])
    print("Error message:", e.args[1])
    sys.exit (1)

cursor = conn.cursor ()
cursor.execute (""" 
                INSERT INTO profile (name,birth,color,foods,cats)
                VALUES(%s,%s,%s,%s,%s)
                """,("Josef", "1971-01-01", None, "eggroll", 4))

但是当我从外壳检查时

mysql> SELECT * FROM profile WHERE name LIKE  'J%';
+----+--------+------------+-------+----------------+------+
| id | name   | birth      | color | foods          | cats |
+----+--------+------------+-------+----------------+------+
|  7 | Joanna | 1952-08-20 | green | lutefisk,fadge |    0 |
+----+--------+------------+-------+----------------+------+

很明显没有插入任何内容,为什么?如果我按照建议添加cursor.commit

    cursor.commit()
AttributeError: 'Cursor' object has no attribute 'commit'
阿妮克特·帕瓦尔

您没有提交交易。

conn.commit()执行查询后,最后添加

cursor = conn.cursor()
cursor.execute (""" 
            INSERT INTO profile (name,birth,color,foods,cats)
            VALUES(%s,%s,%s,%s,%s)
            """,("Josef", "1971-01-01", None, "eggroll", 4))
conn.commit()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章