2013-02-27 86 views
1

我已經在html文檔中創建了一個表單以從user.and中獲取數據,並且我在mysql中創建了一個數據庫。我正在使用python將數據庫連接到表單,以便用戶輸入填充數據庫。但它不起作用。提交值後,我得到了下面的代碼打印,因爲它是在瀏覽器頁面上沒有值從表單插入到數據庫中。你能指出代碼中的錯誤/任何修改嗎?使用通過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

如果你看到純文本,然後Web服務器不處理該文件作爲一個python腳本,轉而把它當作純文本。你使用什麼網絡服務器? – sberry 2013-02-27 17:42:17

+0

我使用了IIS webserver。 – user2115113 2013-02-27 18:13:34

回答

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

+0

謝謝!但代碼仍未在瀏覽器上運行。是否需要在我的Web瀏覽器中單獨進行一些設置以運行代碼? – user2115113 2013-02-27 19:05:24