1
我想插入一些字符串到我的數據庫。爲什麼不使用python插入我的數據庫?
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的連接器,蟒蛇,而是沒有了,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中運行,但是這是一個不同的問題,這個測試是終端上完成)
我在那裏像當前時間戳那樣幾分鐘前,仍然得到相同的錯誤。它適用於這種新的語法。 – munchschair