繁体   English   中英

将Python CGI编程到MySQL中

[英]Python CGI programming into MySQL

我很难让我的SQL插入查询正常工作。 我的Course_Id当前是另一个表CourseMaster的外键。 显然,已经输入了CourseMaster上的所有信息。

Student_Id表单输入对我来说也是一个问号。 我为hidId包含了隐藏的表单类型。 不确定是否正确。 请指教。

import mysql.connector
import cgi
import cgitb;cgitb.enable()
import sys


print "Content-Type: text/html\n\n"

#connection of my database
db = mysql.connector.connect( user='root',password = 'root',
                             host = 'localhost' ,port='8889',database = 'StudentData')


cursor = db.cursor()


form = cgi.FieldStorage()

id=""

first_name = ""

last_name = ""

residential_address = ""

phone_no = ""

Gender = ""

Course_Id = ""

if form.has_key("hidId"):
    id=form["hidId"].value
elif form.has_key("id"):
    id=form["id"].value

if form.has_key("first_name"):
    first_name = form["first_name"].value
    print "<p>name</p>"
    print first_name
if form.has_key("last_name"):
    last_name = form["last_name"].value
    print "<p>name</p>"
    print last_name
if form.has_key("residential_address"):
    residential_address = form["residential_address"].value
    print "<p>residential_address</p>"
    print residential_address
if form.has_key("phone_no"):
    phone_no = form["phone_no"].value
    print "<p>phone_no</p>"
    print phone_no
if form.has_key("Gender"):
    Gender = form["Gender"].value
    print "<p>Gender</p>"
    print Gender
if form.has_key("Course_Id"):
    Course_Id = form["Course_Id"].value
    print "<p>Course_Id</p>"
    print Course_Id

# Insert Data into Table StudentMaster
cursor.execute('''INSERT INTO StudentMaster
                  (Student_Id,Student_FirstName,Student_LastName,Course_Id,Gender,Residential_Address,PhoneNo)
                  VALUES(%s,%s,%s,%s,%s,%s,%s)''',
                  (id,first_name,last_name,Course_Id,Gender,residential_address,phone_no))

cursor.lastrowid


db.commit()

cursor.close()
db.close()

**这是我的错误信息。

**<class 'mysql.connector.errors.IntegrityError'>: 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`studentdata`.`studentmaster`, CONSTRAINT `Course_ID Foreign` FOREIGN KEY (`Course_Id`) REFERENCES `CourseMaster` (`Course_Id`)) 
      args = (1452, '1452 (23000): Cannot add or update a child row: ...rse_Id`) REFERENCES `CourseMaster` (`Course_Id`))', u'23000') 
      errno = 1452 
      message = '' 
      msg = u'Cannot add or update a child row: a foreign key ...rse_Id`) REFERENCES `CourseMaster` (`Course_Id`))' 
      sqlstate = u'23000'****

如果在CourseMaster正确设置了所有ID,则可能是类型问题。 检查表格中的值是否应从字符串转换为数字。 尝试类似

Course_Id = int(Course_Id)

在执行查询之前

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM