基于SQLAlchemy连接mysql库
pymsql插件
import os
import pandas as pd
import pymysql
from sqlalchemy import create_engine,Sequence,text
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
os.chdir('E: /data')
sale = pd.read_csv('sale.csv',encoding = 'GB18030')
'''
sale.csv:
year market sale profit
2010 东 33912 2641
2010 南 32246 2699
2010 西 34792 2574
2010 北 31884 2673
2011 东 31651 2437
2011 南 30572 2853
2011 西 34175 2877
2011 北 30555 2749
2012 东 31619 2106
2012 南 32443 3124
2012 西 32103 2593
2012 北 31744 2962
'''
host = yourhost
user = yourid
password = yourpassword
db = yourdatbasename
port = 3306
charset = 'utf8'
import urllib.parse
password = urllib.parse.quote_plus(password)
engine = create_engine('mysql+pymysql://{user}:{password}@{host}:{port}/{db}?charset={charset}'
.format(user = user,
host = host,
password = password,
db = db,
port = port,
charset = charset),
pool_size = 30,max_overflow = 0
pool_pre_ping=True , pool_recycle=-1, isolation_level="AUTOCOMMIT",
connect_args={
'connect_timeout': 30)
conn = engine.connect()
databaseVersion = conn.execute("SELECT VERSION()").fetchone()
conn.execute('CREATE TABLE sale ('
'year CHAR(20) NOT NULL,'
'market CHAR(20),'
'sale INT ,'
'profit_from_sale INT )')
conn.execute('DROP TABLE sale')
sale.to_sql('sale',conn,if_exists='replace',index = False)
conn.execute('select * from sale').fetchall()
conn.execute('select DISTINCT year,market from sale').fetchall()
conn.execute("select * from sale where year=2012 and market=%s",'东').fetchall()
conn.execute('select year,market,sale,profit from sale order by sale').fetchall()
conn.execute("insert into sale (year,market,sale) value (2010,'东',33912)")
conn.execute("delete from sale")
Base = declarative_base()
class Sale(Base):
__tablename__ = 'sale'
year = Column(String(20), primary_key=True, nullable=False)
market = Column(String(10))
sale = Column(Integer)
profit_from_sale = Column(Integer)
def __repr__(self):
return '%s(%s,%s,%s,%s)'%\
(self.__tablename__,self.year,self.market,self.sale,self.profit_from_sale)
'''
sale表在sql的DDL
CREATE TABLE `sale` (
`year` varchar(20) NOT NULL,
`market` varchar(10) DEFAULT NULL,
`sale` int(11) DEFAULT NULL,
`profit_from_sale` int(11) DEFAULT NULL,
PRIMARY KEY (`year`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
'''
Sale.__table__
class Favor(Base):
__tablename__ = 'favor'
nid = Column(Integer, primary_key=True, autoincrement=True)
caption = Column(String(50), default='red', unique=True)
sale_year = Column(String(10), ForeignKey("sale.year"))
'''
favor表在sql的DDL
CREATE TABLE `favor` (
`nid` int(11) NOT NULL AUTO_INCREMENT,
`caption` varchar(50) DEFAULT NULL,
`sale_year` varchar(10) DEFAULT NULL,
PRIMARY KEY (`nid`),
UNIQUE KEY `caption` (`caption`),
KEY `sale_year` (`sale_year`),
CONSTRAINT `favor_ibfk_1` FOREIGN KEY (`sale_year`) REFERENCES `sale` (`year`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
'''
Base.metadata.create_all(conn)
Base.metadata.drop_all(conn)
Session = sessionmaker(bind=conn)
session = Session()
new = Sale(year=2010, market='东', sale=33912)
session.add(new)
session.add_all([
Sale(year=2011, market='东', sale=31651, profit_from_sale=2437),
Sale(year=2012, market='东', sale=31619),
])
try:
session.commit()
except:
session.rollback()
session.query(Sale.year, Sale.sale).all()
for i in session.query(Sale).order_by(Sale.sale):
print(i.year,i.sale)
for i in session.query(Sale,Sale.year).all():
print(i.Sale,i.year)
for i in session.query(Sale.year.label('test')).all():
print(i.test)
from sqlalchemy.orm import aliased
Sale_test = aliased(Sale, name='sale_test' )
for i in session.query(Sale_test).all()[1:3]:
print(i)
for i in session.query(Sale).filter_by(year = 2012).all():
print(i)
session.query(Sale).filter(text('year>2010')).order_by(text('sale')).all()
session.query(Sale.sale).filter(text('year>2010')).group_by(Sale.sale).all()
session.query(Sale).filter(text('year=:year and market=:market'))\
.params(year = 2011,market ='东').order_by(Sale.sale).one()
session.query(Sale).from_statement(text('select * from sale where year={}'.format(2012))).all()
session.query(Sale.profit_from_sale).count()
from sqlalchemy import func
session.query(func.count(Sale.profit_from_sale)).scalar()
session.query(func.count()).select_from(Sale).scalar()
session.query(Sale.profit_from_sale).distinct().count()
session.query(Sale).filter(Sale.year == 2012).delete()
session.commit()
session.query(Sale).filter(Sale.year == 2010).update({
"profit_from_sale":666})
session.query(Sale).filter(Sale.year == 2010).update({
Sale.profit_from_sale:Sale.profit_from_sale+333})
session.commit()
session.close()
sale.to_sql('sale1',conn,if_exists='append',index = 0,index_label='year',chunksize = None)
readSqlTable1 = pd.read_sql_table('sale1',conn,parse_dates=('year'))
type(readSqlTable1['year'][0])
readSqlTable2 = pd.read_sql_table('sale1',conn,parse_dates={
'year':'%Y-%M-%D'},columns=['year','sale'])
type(readSqlTable2['year'][0])
readSqlTable3 = pd.read_sql_table('sale1',conn,parse_dates={
'year':{
'format':'%Y-%M-%D'}}