美文网首页Data Analysis
python连接mysql数据库

python连接mysql数据库

作者: 戈小蓓 | 来源:发表于2019-12-25 11:49 被阅读0次

    方式一:

    pip install pymysql
    import pymysql
    coon = pymysql.connect(
    host = '127.0.0.1',user = 'root',passwd = '123456',
    port = 3306,db = 'mydb',charset = 'utf8'
    cur = coon.cursor() #建立游标
    cur.execute("select * from stu") #查询数据
    res = cur.fetchall() #获取结果
    print(res)
    cur.close() #关闭游标
    coon.close() #关闭连接
    注意:
    1.port必须写int类型
    2.charset必须写utf8,不能写utf-8

    python 连接 Mysql

    方式二:python使用sqlalchemy连接mysql数据库

    pip install pymysql
    pip install sqlalchemy
    import pymysql
    import sqlalchemy
    from sqlalchemy import create_engine
    engine = create_engine("mysql+pymysql://root:123456@localhost:3306/flask_demo?charset=utf8")
    pd.read_sql(sql,engine,)

    python之sqlalchemy的使用

    案例:
    import pandas as pd
    import numpy as np
    import  sqlalchemy 
    from sqlalchemy import create_engine
    
    def reader(query,db = "data"):
    sql = query
    engine = create_engine("mysql+pymysql://root:123456@localhost:3306/{0}?charset=utf8".format(db)
    df = pd.read_sql(sql,engine,)
    return df
    
    df = reader(
    """
    select * from table where...group by ...
    """
    )
    

    相关文章

      网友评论

        本文标题:python连接mysql数据库

        本文链接:https://www.haomeiwen.com/subject/xlcggctx.html