如何将python中的数据写到mysql数据库中

如题所述

利用mysql插件 pymysql;写insert语句直接插入到数据库

安装:pip install pymysql。

代码:excute_sql方法是执行更新,插入操作。get_datasset方法是查询。

# coding: utf-8
import pymysql.cursors

def execute_sql(sql):
    conn = pymysql.connect(host='127.0.0.1',port = 3306,user='root',passwd='123456',db ='db',charset="utf8")
    try:
        with conn.cursor() as cursor:
            cursor.execute(sql)
            conn.commit()
    finally:
        conn.close()
def get_dataset(sql):
    conn = pymysql.connect(host='127.0.0.1',port = 3306,user='root',passwd='123456',db ='db',charset="utf8")
    try:
        with conn.cursor() as cursor:
            cursor.execute(sql)
            return cursor.fetchall()
    finally:
        conn.close()
温馨提示:答案为网友推荐,仅供参考
相似回答