import pymysql
import configparser

def login_mysql():
    #获取配MySQL的用户置文件并连接
    config=configparser.ConfigParser()
    config.read('config.ini')
    host=config.get('MYSQL','host')
    port=config.get('MYSQL','port')
    user = config.get('MYSQL', 'user')
    password = config.get('MYSQL', 'password')
    database = config.get('MYSQL', 'database')
    db = pymysql.connect(host=host,port=int(port),user=user,password=password,database=database)
    cursor=db.cursor()
    #新建表51job
    sql1='drop table if exists 51job'
    sql2='''create table 51job(job_name varchar(50),company_name varchar(50),salary varchar(30),address varchar(50),experience varchar(30),level varchar(20),info varchar(9999),welfare varchar(999),url varchar(999))'''
    try:
        cursor.execute(sql1)
        cursor.execute(sql2)
        db.commit()
    except Exception as e:
        print(e)
        db.rollback()
    return db,cursor

写入数据

sql="insert into job_data values('%s','%s','%s','%s','%s','%s','%s','%s','%s')" %(job_name,company_name,salary,address,experience,level,job_info,welfare,href)
try:
    cursor.execute(sql)
    db.commit()
    print('成功')
except Exception as e:
    print(e)
    db.rollback()
cursor.close()
db.close()
Last modification:April 19th, 2020 at 05:52 pm
If you think my article is useful to you, please feel free to appreciate