python笔记(pymysql基本用法)连接mysql数据库

import pymysql
MYSQL_HOST = '127.0.0.1'
MYSQL_DBNAME = 'bgh'         #数据库名字,请修改
MYSQL_USER = 'root'             #数据库账号,请修改
MYSQL_PASSWD = ''         #数据库密码,请修改
MYSQL_PORT = 3306               #数据库端口,在dbhelper中使用

#数据库保存
def data_save(data):
    # 打开数据库连接
    conn = pymysql.connect(
        host=MYSQL_HOST,
        user=MYSQL_USER,
        password=MYSQL_PASSWD,
        database=MYSQL_DBNAME,
        charset="utf8")
    # 创建数据游标,数据库连接对象
    tx = conn.cursor()
    # 写入数据库中
    try:
        sql = "SELECT `url` FROM `brands` WHERE `url`='%s'" % (str(data['url']))
        tx.execute(sql)
        result = tx.fetchone()
        if result is not None:
            sql = "UPDATE `brands` SET `news_num`=%s,`jieshao`='%s'  WHERE `brand`='%s'" % (
            int(data['news_num']),str(data['jieshao']).replace('None','null'),str(data['brand']))
            tx.execute(sql)
            print(10 * '☆' + '当前地址已存在' + 10 * '☆')
        else:
            sql = "insert into  
brands(brand,url,type,retype,news_num,created_at,jieshao)  " \
                  "values(%s,%s,%s,%s,%s,%s,%s)"
            params = (data["brand"], data['url'], data['type'], data['retype'], data['news_num'], data['created_at'],data['jieshao'])
            tx.execute(sql, params)
            print(10 * '#' + '当前数据已成功入库' + 10 * '#')
    except Exception:
        # 如果发生异常,则回滚
        print("数据入库发生异常", Exception)
        conn.rollback()
    conn.commit()
    tx.close()
    conn.close()

你可能感兴趣的:(python,mysql,python,big,data)