python3操作mysql

1.从MySQL数据库读取目标表数据,并处理

import pandas as pd
import pymysql

## 加上字符集参数,防止中文乱码
dbconn=pymysql.connect(
  host="**********",
  database="kimbo",
  user="kimbo_test",
  password="******",
  port=3306,
  charset='utf8'
 )
  
#sql语句
sqlcmd="select col_name,col_type,col_desc from itf_datadic_dtl_d limit 10"
  
#利用pandas 模块导入mysql数据
a=pd.read_sql(sqlcmd,dbconn)
#取前5行数据
b=a.head()
print(b)

2.获取某个数据库有哪些表

import  pymysql

# 打开数据库连接
conn = pymysql.connect(host='127.0.0.1', user='root', passwd='222000', db='test')
# 测试下数据库连接成功不成功
print(conn)
# 使用cursor()方法获取操作游标
cur = conn.cursor()
# SQL插入语句
sql = "show tables"
# 执行sql语句
cur.execute(sql)
# 获取所有记录列表
results = cur.fetchall()
print(results)
# 关闭数据库连接
conn.close()

3. ORM框架

from sqlalchemy import create_engine
engine = create_engine('mysql+pymysql://root:*****@129.207.298.179:3306/graylog?charset=utf8',
                       encoding='utf-8')
sql = "show tables"
result = engine.execute(sql)
res = result.fetchall()
print(res)
conn = create_engine('mysql+pymysql://root:[email protected]:3306/graylog?charset=utf8', encoding='utf-8')
a = pd.read_sql_table('2017-04', conn)
# 有时上面的那条会报错,用下面这个看看可以不
firmware = pd.read_sql_query('select * from firmname',  conn)

你可能感兴趣的:(python3操作mysql)