网页插入数据mysql数据库

文件目录结构:

                  

前端用户输入页面:

forms.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/cgi-bin/saveData.py" method="post">
        <p>
            <label>姓名</label>
            <input type="text" name="username">
        </p>
        <p>
            <label>年龄</label>
            <input type="text" name="age">
        </p>
        <p>
            <input type="submit" value="按我呀">
        </p>

    </form>
</body>
</html>

页面展示:

jump.py  显示提交结果

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 :
    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)

页面展示:

index.py

import pymysql

db = pymysql.connect(
    host = "localhost",
    user = "root",
    password = "admin",
    database = "school",
    port = 3306,
    charset = 'utf8'
)

cursor = db.cursor()

exe = cursor.execute("select name,age,gender,address from person")

result = cursor.fetchall()

db.commit()
cursor.close()
db.close()

li = ''
for a in result:
    li += '<li>姓名:%s |年龄:%s| 性别:%s| 地址:%s</li>'%a

html = """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="gbk">
    <title>Title</title>
    <style>
    
    ul{
    width:450px;
    list-style:none;
    margin:0 auto;
    }
    li{
    font-size:20px;
    margin:10px
    }
    
    </style>
</head>
<body>
    <h1 style="color: red">
        下面是VIP用户
    </h1>
    <ul>
        %s
    </ul>
</body>
</html>
"""%li

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

页面展示:

猜你喜欢

转载自blog.csdn.net/weixin_42223833/article/details/88671693
今日推荐