网上很多代码给的连接数据库是连的sqlite的例子,按照以下方法写没问题,我还用了ORM
# -*- coding:utf-8 -*-
from sqlalchemy import create_engine,Column,Integer,String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
dbPath = 'sqlite:////Users/mbp/Downloads/JA.db'
engine = create_engine(dbPath,echo=True)
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base()
class Actresses(Base):
__tablename__ = 'JA_NAME'
id = Column('id', Integer, primary_key=True, autoincrement=True)
name = Column('NAME_URL',String)
nameUrl = Column('NAME',String)
act = session.query(Actresses).all()
print act
如果有同学依葫芦画瓢把数据库地址直接改成mysql的连接就会报错
raise EnvironmentError("%s not found" % (mysql_config.path,))
原因是使用sqlalchemy连接mysql的话光安装sqlalchemy这个库还不够,还要安装mysql-python这个驱动库
装好后,代码中也不需要
import
,直接运行下就好了,完整代码如下,重点就是在安装了sqlalchemy之后还要再安装下mysql-python
# -*- coding:utf-8-*-
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String
from sqlalchemy.sql import select
import re
metadata = MetaData()
print_order = Table('print_order', metadata,
Column('id', Integer, primary_key=True, autoincrement=True),
Column('order_id', String),
Column('Ten_or_Ali_order_id', String),
Column('payment_state', String),
Column('fee', String),
Column('print_num', String),
Column('consignee_name', String),
Column('consignee_phone', String),
Column('consignee_addr', String),
Column('origin_pic_name', String),
Column('final_pic_name', String),
Column('print_pic_name', String),
Column('origin_pic_name', String),
Column('spec_name', String),
Column('serial_number', String),
Column('payment_time', String)
)
class LeQiMySQL(object):
def __init__(self):
self.dbPath = 'mysql://root:root@127.0.0.1:3306/DB_NAME'
self.engine = create_engine(self.dbPath, encoding='utf-8', echo=True)
self.conn = self.engine.connect()
print 'LeQiMySQl init'
def searchPrintOrderWithSerialNumber(string):
phoneNum = re.match(r"0?(13|14|15|16|17|18)[0-9]{9}", string)
print phoneNum
db = LeQiMySQL()
end