使用通过python连接的表单在数据库中插入数据

时间:2013-02-27 17:40:05

标签: python mysql html-form

我在html文档中创建了一个表单来从用户那里获取数据。我在mysql中创建了一个数据库。我使用python将数据库连接到表单,以便用户输入填充数据库。但它不起作用。提交值后,我将在浏览器页面上打印以下代码,并且没有值从表单插入数据库。你能指出代码中的错误/任何修改吗?

import cgitb;cgitb.enable()
import MySQLdb
import cgi
import sys

form=cgi.FieldStorage()
Text0=form.getValue('Text0')
Text1=form.getValue('Text1')
Text2=form.getValue('Text2')
Text3=form.getValue('Text3')
Text4=form.getValue('Text4')

# Open database connection
dbc = MySQLdb.connect("127.0.0.1","root","sam143","project" )

# prepare a cursor object using cursor() method
cursor = dbc.cursor()

# Prepare SQL query to INSERT a record into the database.

sql = """INSERT INTO entries(slno, \
       dat1, dat2, dat3, dat4, dat5) \
       VALUES ('%d', '%d', '%d', '%d', '%d', '%d' )""" % \
       (l[0], l[1], l[2], l[3], l[4])

try:
   # Execute the SQL command
   cursor.execute(sql)
   sql = "SELECT * FROM entries"
   cursor.execute(sql)
   print cursor.fetchall()
   # Commit your changes in the database
   dbc.commit()

except:
   # Rollback in case there is any error
   dbc.rollback()

# disconnect from server
dbc.close()

1 个答案:

答案 0 :(得分:1)

>>> form=cgi.FieldStorage()
>>> dir(form)
['FieldStorageClass', '_FieldStorage__write', '__contains__', '__doc__', '__getattr__', '__getitem__', '__init__', '__iter__', '__len__', '__module__', '__nonzero__', '__repr__', 'bufsize', 'disposition', 'disposition_options', 'done', 'fi
le', 'filename', 'fp', 'getfirst', 'getlist', 'getvalue', 'has_key', 'headers', 'innerboundary', 'keep_blank_values', 'keys', 'length', 'list', 'make_file', 'name', 'outerboundary', 'qs_on_post', 'read_binary', 'read_lines', 'read_lines_to
_eof', 'read_lines_to_outerboundary', 'read_multi', 'read_single', 'read_urlencoded', 'skip_lines', 'strict_parsing', 'type', 'type_options']
>>> 

form.getvalue不是form.getValue