python操作数据库3.x

通过该方法可以将dataframe直接写入数据库,省了很多麻烦

    conn = create_engine('mysql+pymysql://root:123qwe@localhost:3306/sem?charset=utf8')
    dataFrame = pd.read_excel(path)
    dataFrame['date'] = [time.strftime("%Y-%m-%d")]*len(dataFrame)
    dataFrame.to_sql('sem_real', con=conn, if_exists='append', index=False, index_label=False)

标准的pymysql流程

 db = pymysql.connect("localhost", "root", "123qwe", "sem")
 cursor = db.cursor()

data = {
    'id': '20120001',
    'name': 'Bob',
    'age': 20
}

 table = 'semrealtime'
 keys = ','.join(dataJson.keys())
 values = ','.join(['%s'] * len(dataJson))

 sql = "INSERT INTO {table}({keys}) VALUE ({values})".format(table=table, keys=keys, values=values)


try:
    cursor.execute(sql, tuple(data.values()))
    db.commit()
except:
    # 发生错误时回滚
    db.rollback()

# 关闭数据库连接
db.close()

你可能感兴趣的:(python操作数据库3.x)