You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求修正:验证邮箱格式并插入MySQL的Python代码

修正后的邮箱验证与MySQL插入代码

原代码存在的问题及修正点:

  • 正则表达式不符合需求:原正则允许.和_出现在前缀部分,不符合「字母/数字组成表达式」的规则,同时域名部分限制过窄(仅允许2-3位后缀),调整为匹配需求的正则。
  • 验证逻辑无效:原函数在输入无效邮箱时,重新输入的邮箱未同步到外部变量,且没有循环验证直到输入有效。
  • SQL注入风险:直接将变量拼接进SQL语句,改用参数化查询避免注入问题。
  • 资源未清理:未关闭数据库游标与连接,添加资源释放逻辑。
  • 密码输入不安全:明文输入密码,改用getpass模块隐藏输入内容。

修正后的代码:

import re
import mysql.connector
from getpass import getpass

def validate_email(email):
    # 匹配「字母/数字组成的表达式@字符串.字符串」规则的正则
    regex = r'^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+$'
    return re.fullmatch(regex, email) is not None

def get_valid_email():
    while True:
        email = input("Enter email address: ")
        if validate_email(email):
            return email
        print("Invalid Email")
        print("Enter correct format: expression@string.string")

if __name__ == '__main__':
    # 获取有效邮箱和密码
    email = get_valid_email()
    password = getpass("Enter password: ")

    # 数据库操作
    cnx = None
    cursor = None
    try:
        cnx = mysql.connector.connect(
            user='root',
            password='',
            host='127.0.0.1',
            database='username_password'
        )
        cursor = cnx.cursor()
        # 参数化查询避免SQL注入
        insert_query = "INSERT INTO _info (email, password) VALUES (%s, %s)"
        cursor.execute(insert_query, (email, password))
        cnx.commit()
        print("Data inserted successfully!")
    except mysql.connector.Error as err:
        print(f"Database error: {err}")
        if cnx:
            cnx.rollback()
    finally:
        # 关闭资源
        if cursor:
            cursor.close()
        if cnx:
            cnx.close()

内容的提问来源于stack exchange,提问作者Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 11:15:32