我使用python在html中创建了一个表,我想将这些输入表值添加到sql数据库

时间:2016-11-17 04:39:03

标签: python html mysql sql-server

我正在使用python访问html来创建一个表,而我正在尝试做的是当用户输入值并单击一个提交按钮时,所有值都将保存在“students”表中。我不知道如何使用提交按钮来保存所有值(姓氏,名字,中间名,最终名,第一名,第二名,第三名)。 我不熟悉pymysql,我浏览了很多网站,找到解决这个问题的方法。我接受任何建议。

import cgitb
import pymysql
cgitb.enable()
print("Content-type: text/html\n")

print('<form method="" action="">',
          '<fieldset>',
              '<legend>Personal information:</legend>',
              'Last name:'
              '<input type="text" name="lastname" value="lastname"><br>',
              'First name:'
              '<input type="text" name="firstname" value="firstname"><br>',
              'MidtermGrade:'
              '<input type="text" name="midtermgrade" value="midtermgrade"><br>',
              'FinalGrade:'
              '<input type="text" name="finalgrade" value="finalgrade"><br>',
              'FirstHW:'
              '<input type="text" name="firsthw" value="firsthw"><br>',
              'SecondHW:'
              '<input type="text" name="secondhw" value="secondhw"><br>',
              'ThirdHW:'
              '<input type="text" name="thirdhw" value="thirdhw"><br>',
              '<br><br>'
              '<input type="submit" value="Submit">',
          '</fieldset>'
     </form>)

建立与RDS实例上的数据库的连接。替换为您自己的服务器和用户凭据。

conn = pymysql.connect(host=localhost, port=3306, user='username', passwd='password', db='student')
cur = conn.cursor()

一些SQL返回一些数据

cur.execute("SELECT * from students")

化妆品的空白区域

迭代结果集,一次打印一行

关闭连接

cur.close()
conn.close()

2 个答案:

答案 0 :(得分:0)

我认为您需要的不仅仅是打印声明才能获得可用的表格 您已经创建了一个HTML表单,但是将用户数据从它发送到服务器,因此您可以获取这些值需要Web服务器。

我建议您查看 Flask (或其他)Web框架:http://flask.pocoo.org/
它非常容易上手,您可以将表单数据作为Python函数中的变量获取;然后你可以调用你的SQL函数将它们保存到数据库中 让我们知道你的进展!

答案 1 :(得分:0)

这种方法不起作用,因为你正在尝试构建页面服务器端,然后期望输入客户端,然后做一些更多的服务器端工作来构建页面。但是(我自己也不是这方面的专家,所以我会感谢更正),一旦你构建了页面服务器端,并将其发送到客户端,你需要在客户端上使用某种形式的JavaScript来获取任何来自服务器的更多信息(AJAX是一种常见的方式)。

如果您可以使用submit按钮将用户带到另一个页面查看结果,那么您就不需要Javascript。我会构建你想要做的事情(请记住,我现在无法对此进行测试,因此您必须对其进行调试):

在档案form.html中:

<!-- TODO: put the rest of the HTML here -->
<form method="post" action="get_results.py">
    <fieldset>
        <legend>Personal information:</legend>
        Last name:
        <input type="text" name="lastname" value="lastname"><br>
        First name:
        <input type="text" name="firstname" value="firstname"><br>
        MidtermGrade:
        <input type="text" name="midtermgrade" value="midtermgrade"><br>
        FinalGrade:
        <input type="text" name="finalgrade" value="finalgrade"><br>
        FirstHW:
        <input type="text" name="firsthw" value="firsthw"><br>
        SecondHW:
        <input type="text" name="secondhw" value="secondhw"><br>
        ThirdHW:
        <input type="text" name="thirdhw" value="thirdhw"><br>
        <br><br>
        <input type="submit" value="Submit">
    </fieldset>
</form>

请注意,我在表单中填写了actionmethod属性。这是纯HTML。提交表单后,用户将被重定向到get_results.pyget_results.html必须通过表单读取附加到页面请求的POST信息。

类似的东西:

在档案import cgi import cgitb import pymysql cgitb.enable() # This *should* get the fields from the previous form. # I can't test it now though... form = cgi.FieldStorage() # this part is almost straight from https://github.com/PyMySQL/PyMySQL import pymysql.cursors # Connect to the database connection = pymysql.connect(host='localhost', user='user', password='passwd', db='db', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: student_sql = 'INSERT INTO `students` (lastname, firstname) VALUES (%s, %s)' cursor.execute(student_sql,(form['lastname'], form['firstname']) ) # replacing some filed names with '...'. Fill them in grade_sql = 'INSERT INTO `grades` (midtermgrade, finalgrade, ...) VALUES (%d, %d, %d, %d)' cursor.execute(grade_sql, form['midtermgrade'], form['finalgrade'], ...) connection.commit() with connection.cursor() as cursor: # Read a single record sql = "SELECT * FROM students" cursor.execute(sql)) for result in cursor.fetchall(): print(result, '<br>') finally: connection.close() 中:

  let _: NSData!
        do {
            let priorBounds = table_view.bounds
            let fittedSize = table_view.sizeThatFits(CGSizeMake(priorBounds.size.width, .infinity))
            table_view.bounds = CGRectMake(0, 0, fittedSize.width, fittedSize.height)
            let pdfPageBounds = CGRectMake(0, 0, 612, 800)
            let pdfData = NSMutableData()
            UIGraphicsBeginPDFContextToData(pdfData, pdfPageBounds, nil)
            do {
                var pageOriginY = 0
                while pageOriginY < Int(fittedSize.height)  {
                    UIGraphicsBeginPDFPageWithInfo(pdfPageBounds, nil)
                    CGContextSaveGState(UIGraphicsGetCurrentContext()!)
                    do {
                        CGContextTranslateCTM(UIGraphicsGetCurrentContext()!, 0, -CGFloat(pageOriginY))
                        table_view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
                    }
                    CGContextRestoreGState(UIGraphicsGetCurrentContext()!)
                    pageOriginY += Int(pdfPageBounds.size.height)
                }
            }
            UIGraphicsEndPDFContext()
            table_view.bounds = priorBounds
            if let documentDirectories = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first {
                let documentsFileName = documentDirectories + "/" + (filename as String)
                debugPrint(documentsFileName)
                pdfData.writeToFile(documentsFileName, atomically: true)
            }
        }

这可能是最简单的方法。但是,重要的是要知道,这种方法不会扩展到更大的项目。 对于初学者,您需要:

  • 模板语言,因此您可以将原始HTML和插入其中的代码分开
  • URL操作(所以像mysite.com //grades会让用户直接达到他们的成绩)
  • 用户身份验证(不希望学生查看其他学生成绩吗?)
  • 一个ORM,而不是直接处理你的数据库(我不会在这里放置尽可能多的股票,但有些人发誓)

如果您尝试制作比这更大的内容,请查看适用于Python的FlaskDjango框架,或其他任何语言的其他解决方案。