2017年8月8日 星期二

sqlalchemy連接mysql錯誤

要連到mysql測試如下
db_engine = create_engine('mysql://root:admin@123@localhost/testdb')
出現錯誤「ImportError: No module named MySQLdb」

是因為少了相對應的模組,安裝如下:
pip install pymysql

然後改為:
db_engine = create_engine('mysql+pymysql://root:admin@123@localhost/testdb')
就沒問題了

接著就可以create table
resultProxy = db_engine.execute("CREATE TABLE IF NOT EXISTS testdb(uuid text NOT NULL, time text NOT NULL, data text)")

插入資料:
uuid = '123456789012345'
my_time = time.strftime("%Y-%m-%d %H:%M:%S")
data = '{ "ai": [ 26, 115 ], "do": [ 1, 0 ] }'
resultProxy=db_engine.execute("insert into rtudb (uuid, time, data) values('%s', '%s', '%s')" %(uuid, my_time, data))

查資料
resultProxy=db_engine.execute("select * from rtudb where uuid = '%s' and time >= '%s'" %('123456789012345', '2017'))

userList = resultProxy.fetchall()
print(userList)


沒有留言:

張貼留言