为什么使用python将这个插入到我的数据库中?

时间:2015-12-18 14:48:21

标签: python mysql sql python-2.7

我想在我的数据库中插入一些字符串。

import mysql.connector
import web

from mysql.connector import Error
import cgi, cgitb

conn = mysql.connector.connect(host='localhost', database='adatabase', user='root', password='')
cursor = conn.cursor()

if conn.is_connected():
    print('Connected to MySQL database')



fullname = "fullname"
email ="email"
comments = "comments"
sql = """INSERT INTO `comments` (`id`, `name`, `email`, `comments`, `time`) VALUES (NULL, %s, %s, %s, )""" % (fullname, email, comments)

cursor.execute(sql)
conn.commit()  
cursor.close()
conn.close()

它给了我这个错误。注意,我在安装mysql-connector-python_1.2.3时遇到了这个错误。

Connected to MySQL database
Traceback (most recent call last):
  File "commentsscript.cgi", line 108, in <module>
    cursor.execute(sql)
  File "/usr/lib/python2.7/dist-packages/mysql/connector/cursor.py", line 494, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 683, in cmd_query
    statement))
  File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 601, in _handle_result
    raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ')' at line 1

当我没有安装mysql-connector-python时,我也遇到了这个错误,而是mysqlworkbench

Traceback (most recent call last):
  File "commentsscript.cgi", line 108, in <module>
    cursor.execute(sql)
  File "/usr/lib/python2.7/dist-packages/mysql/connector/cursor.py", line 494, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 683, in cmd_query
    statement))
  File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 601, in _handle_result
    raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'fullname' in 'field list'

我尝试过的事

将变量传递给create table语句。这有效。

anooog1 = "thing"
sql = """CREATE TABLE thiga (%s INT, COL2 INT )""" % (anooog1) 

也直接传递字符串。考虑到我希望最终从HTML传递变量,这是多余的。我一直在测试语法。

sql = """INSERT INTO `comments` (`id`, `name`, `email`, `comments`, `time`) VALUES (NULL, "fullname", "email", "comments", CURRENT_TIMESTAMP)"""

(我也很难让cgi脚本在apache中运行,但这是一个不同的问题,这个测试正在终端上完成)

1 个答案:

答案 0 :(得分:1)

不要使用字符串格式将变量插入SQL查询 - 这至少会使您的代码容易受到SQL injections的攻击。<​​/ p>

您还缺少查询中time列的值,我很确定您必须将占位符放入引号(%s - &gt; "%s")。

无论如何,参数化您的查询

sql = """
    INSERT INTO 
        comments 
        (id, name, email, comments, time) 
    VALUES 
        (NULL, %s, %s, %s, CURRENT_TIMESTAMP)
"""
cursor.execute(sql, (fullname, email, comments))

请注意,此处不需要占位符周围的引号 - 在这种情况下,数据库驱动程序会自动处理类型转换。