2018-11-02
閱讀量:
905
python 讀寫MySQL數(shù)據(jù)庫
SQLAlchemy是Python編程語言下的一款ORM框架,該框架建立在數(shù)據(jù)庫API之上,使用關(guān)系對象映射進行數(shù)據(jù)庫操作,簡言之便是:將對象轉(zhuǎn)換成SQL,然后使用數(shù)據(jù)API執(zhí)行SQL并獲取執(zhí)行結(jié)果。

SQLAlchemy本身無法操作數(shù)據(jù)庫,其必須使用pymsql等第三方插件,不同插件對應(yīng)的語句如下:
MySQL-Python mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname>
pymysql mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
MySQL-Connector mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname>
cx_Oracle oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...]
python實現(xiàn)代碼如下
#導(dǎo)入相關(guān)包
from sqlalchemy import create_engine
#定義鏈接參數(shù)
db_info = {
'user': 'root',
'password': 'emtf',
'host': 'localhost',
'database': 'test'
}
#根據(jù)鏈接參數(shù)鏈接數(shù)據(jù)庫
engine = create_engine('mysql://%(user)s:%(password)s@%(host)s/%(database)s?charset=utf8'% db_info, encoding='utf-8')
#對數(shù)據(jù)庫進行操作
reslt = engine.execute("select * from titanics;")
#查看返回的結(jié)果
list(reslt)







評論(0)


暫無數(shù)據(jù)
推薦帖子
0條評論
0條評論
0條評論
1條評論