简单的数据库数据管理(添加、查看)

83 阅读1分钟

注:

     提前创建:  表 student   

create table student(id int primary key auto_increment,age int,gender char(20),address char(50));

一、信息提交页面(HTML) 

form.html    -->  提交后跳转   提示添加状况页面jump.py

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="gbk">
    <title>提交页面</title>
</head>
<body>
    <form action="cgi-bin/jump.py" method="post">
        <p>
            <label>姓名</label>
            <input type="text" name="username">
        </p>
        <p>
            <label>年龄</label>
            <input type="text" name="age">
        </p>
        <p>
            <label>性别</label>
            <input type="text" name="gender">
        </p>
        <p>
            <label>籍贯</label>
            <input type="text" name="address">
        </p>
        <input type="submit" value="提交">
     </form>
</body>
</html>

二、存入数据库,并返回提交情况页面

import cgi
import pymysql

html = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="gbk">
    <title>Title</title>
</head>
<body>
    <p> %s </p>
</body>
</html>
"""

//从前台获取用户输入的信息
requestData = cgi.FieldStorage()
name = requestData.getvalue('username')
age = requestData.getvalue('age')
gender = requestData.getvalue('gender')
address = requestData.getvalue('address')
if name and age and gender and address:
    sql = "INSERT INTO person(name,age,gender,address) value('%s',%s,'%s','%s')"%(name,age,gender,address)
    try:
        db = pymysql.connect(
            host="localhost",
            user="root",
            password="admin",
            database="school",
            port=3306,
            charset='utf8'
        )
        cursor = db.cursor()
        exe = cursor.execute(sql)
        db.commit()
        cursor.close()
        db.close()
    except Exception as e:
        html = html%str(e)
    else:
        html = html % "保存成功<a href='index.py'>点我跳转</a>"


print("Content-type:text/html;charset:utf8")

print("\n")
print(html)