• python 用 pymysql 向数据表插入数据


    一、 加载库、封装函数

    import pandas as pd
    import pymysql
    
    def mycursor(db_name=None):
        '''连接数据库,创建游标'''
        config = dict(zip(['host', 'user', 'port', 'password'],
                          ['192.168.137.155', 'shanger', 3306, '0123']))
        config.update(database=db_name)
        connection = pymysql.connect(**config)
        cursor = connection.cursor()
        return cursor
    
    def use(db_name):
        '''切换数据库,返回游标'''
        return mycursor(db_name)
    
    def insert_many(table, data):
        '''向全部字段插入数据'''
        val = '%s, ' * (len(data[0])-1) + '%s'
        sql = f'insert into {table} values ({val})'
        cursor.executemany(sql, data)
        cursor.connection.commit()
        
    def query(sql):
        '''以数据框形式返回查询据结果'''
        cursor.execute(sql)
        data = cursor.fetchall()  # 以元组形式返回查询数据
        header = [t[0] for t in cursor.description]
        df = pd.DataFrame(list(data), columns=header)  # pd.DataFrem 对列表具有更好的兼容性
        return df
    def select_database(): '''查看当前数据库''' sql = 'select database();' return query(sql) def show_tables(): '''查看当前数据库中所有的表''' sql = 'show tables;' return query(sql) def select_all_from(table): sql = f'select * from {table};' return query(sql)

    二、插入数据

    1、选则数据库、查看数据

     2、插入数据

    data = [
     ('德岛', '100'),
     ('香川', '200'),
     ('爱媛', '150'),
     ('高知', '200'),
     ('福冈', '300'),
     ('佐贺', '100'),
     ('长崎', '200'),
     ('东京', '400'),
     ('群马', '50')]
    
    insert_many('poptbl', data)
    select_all_from('poptbl')

     

  • 相关阅读:
    8.7题解
    2019.9.16 csp-s模拟测试44 反思总结
    洛谷P3168 [CQOI2015]任务查询系统
    洛谷P2468 [SDOI2010]粟粟的书架
    2019.8.14 NOIP模拟测试21 反思总结
    2019.8.13 NOIP模拟测试19 反思总结
    2019.8.12 NOIP模拟测试18 反思总结
    大约是个告别【草率极了】
    2019.8.10 NOIP模拟测试16 反思总结【基本更新完毕忽视咕咕咕】
    2019.8.9 NOIP模拟测试15 反思总结
  • 原文地址:https://www.cnblogs.com/shanger/p/12982357.html
Copyright © 2020-2023  润新知