MySQLdb执行INSERT到表

时间:2015-03-07 16:18:11

标签: python mysql mysql-python

我是MySql和MySQLdb的新手。但我已经尝试了几个小时来解决这个问题。

我有一张这样的表:

  

的MySQL> DESCRIBE用户;

+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| id       | int(11)     | NO   | PRI | NULL    | auto_increment |
| username | varchar(25) | YES  |     | NULL    |                |
| password | varchar(25) | YES  |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+

代码部分:

def connect_db():
    conn = MySQLdb.connect(user='root',
                            passwd='',
                            db='flask',
                            host='localhost')
    return conn


cur = connect_db().cursor()


cur.execute("DROP TABLE IF EXISTS users")
cur.execute("CREATE TABLE users(id INT PRIMARY KEY AUTO_INCREMENT, \
                username VARCHAR(25), password VARCHAR(25))")

str = "INSERT INTO users ('id', 'username', 'password') VALUES (NULL, %s, %s)"

cur.execute(str % ('admin', 'password'))

我收到了这样的错误:

> Traceback (most recent call last):   File
> "C:\Users\Emil\Desktop\flaskr\flaskr.py", line 29, in <module>
>     cur.execute(str % ('admin', 'password'))   File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 202, in
> execute
>     self.errorhandler(self, exc, value)   File "C:\Python27\lib\site-packages\MySQLdb\connections.py", line 36, in
> defa lterrorhandler
>     raise errorclass, errorvalue
> _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL synta ; check the manual that corresponds to your MySQL server
> version for the right yntax to use near ''id', 'username', 'password')
> VALUES (NULL, admin, password)  at line 1")

我猜我的INSERT命令有问题。我不知道该怎么做,并试图搜索可能有助于谷歌的内容。

1 个答案:

答案 0 :(得分:0)

以下是您使用当前解决方案获得的结果查询:

INSERT INTO users ('id', 'username', 'password') VALUES (NULL, admin, password)

如您所见,adminpassword周围没有引号 - 这就是ProgrammingError例外的原因。

除此之外,通过字符串格式插入查询参数会使您的代码容易受到SQL注入


相反,参数化查询

query = """
    INSERT INTO 
        users 
        ('id', 'username', 'password') 
    VALUES 
        (NULL, %s, %s)
"""

cur.execute(query, ('admin', 'password'))