python 连接mysql数据库

…衆ロ難τιáo~ 提交于 2019-11-29 15:05:08

连接数据库需要先pip install PyMySQL

import pymysql
import re

def spotSql(dbhost,dbport,dbuser,dbpasswd,dbdatabase,dbsql):
    # 打开数据库连接
    db = pymysql.connect(host=dbhost,
                         port=dbport,
                         user=dbuser,
                         passwd=dbpasswd,
                         database=dbdatabase)
    # 使用cursor()方法获取操作游标
    cur = db.cursor()
    # 使用execute方法执行SQL语句
    cur.execute(dbsql)
    # 使用 fetchone() 方法获取一条数据
    data = cur.fetchall()
    # 关闭数据库连接
    db.close()
    return data

if __name__ == '__main__':
    db_host = 'localhost'
    db_port = 'port'
    db_user = 'test'
    db_passwd = '123456'
    db_database = 'msgemail'
    mysqltest = "select * from table"

    response = spotSql(db_host, db_port, db_user, db_passwd, db_database, mysqltest)
    #显示查询结果
    b = response[0][0]
    # print("**************response**************:",response)
    code = re.findall(r"验证码:(.+?),验证码", b)
    print("**************code**************:",code)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!