这是我为一些软件(Anki)编写插件的一些代码。
for i in date:
self.deck.s.execute(
"""CASE WHEN EXISTS(SELECT * FROM :table WHERE day=date( :i )) THEN
UPDATE :table SET WHERE day=date(:i)
ELSE
INSERT INTO :table (day, matureRise) VALUES ( date( :i ),1)
END""", {'table':STATSTABLE,'i':i})
问题是它不断抛出一个OperationalError。具体来说,我得到了:
sqlalchemy.engine.default", line 299, in do_execute
OperationalError: (OperationalError) near "CASE": syntax error u'CASE WHEN EXISTS(SELECT * FROM ? WHERE day=date( ? )) THEN\nUPDATE ? SET WHERE day=date(?)\nELSE\nINSERT INTO ? (day, matureRise) VALUES ( date( ? ),1) END' ('stats_2', (u'2011-05-03',), 'stats_2', (u'2011-05-03',), 'stats_2', (u'2011-05-03',))
我已经尝试了很多东西,但我无法弄清楚什么是错的。我对sqlalchemy不是很熟悉,所以我想知道是否在提供我缺少的原始SQL方面存在一些细微差别。
答案 0 :(得分:0)
试试这个
from sqlalchemy import create_engine
engine = create_engine('mysql://test:test@localhost/test', echo=True)
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Date, Column, Integer
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True, autoincrement=True)
day = Column(Date, unique=True)
if __name__ == '__main__':
Base.metadata.create_all(engine)
c = engine.connect()
c.execute("""INSERT INTO users(day) VALUES ('2012-03-05') ON DUPLICATE KEY UPDATE day='2012-03-04'""")
当我第一次运行此文件时,我得到了像
这样的日志2012-03-05 12:39:42,202 INFO sqlalchemy.engine.base.Engine SELECT DATABASE()
2012-03-05 12:39:42,202 INFO sqlalchemy.engine.base.Engine ()
2012-03-05 12:39:42,204 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'character_set%%'
2012-03-05 12:39:42,204 INFO sqlalchemy.engine.base.Engine ()
2012-03-05 12:39:42,205 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'lower_case_table_names'
2012-03-05 12:39:42,205 INFO sqlalchemy.engine.base.Engine ()
2012-03-05 12:39:42,206 INFO sqlalchemy.engine.base.Engine SHOW COLLATION
2012-03-05 12:39:42,206 INFO sqlalchemy.engine.base.Engine ()
2012-03-05 12:39:42,209 INFO sqlalchemy.engine.base.Engine SHOW VARIABLES LIKE 'sql_mode'
2012-03-05 12:39:42,209 INFO sqlalchemy.engine.base.Engine ()
2012-03-05 12:39:42,210 INFO sqlalchemy.engine.base.Engine DESCRIBE `users`
2012-03-05 12:39:42,210 INFO sqlalchemy.engine.base.Engine ()
2012-03-05 12:39:42,211 INFO sqlalchemy.engine.base.Engine INSERT INTO users(day) VALUES ('2012-03-05') ON DUPLICATE KEY UPDATE day='2012-03-04'
2012-03-05 12:39:42,211 INFO sqlalchemy.engine.base.Engine ()
2012-03-05 12:39:42,212 INFO sqlalchemy.engine.base.Engine COMMIT
然后我检查数据库
mysql> select * from users;
+----+------------+
| id | day |
+----+------------+
| 8 | 2012-03-05 |
+----+------------+
1 row in set (0.00 sec)
然后我再次运行程序
再次检查mysql。
mysql> select * from users;
+----+------------+
| id | day |
+----+------------+
| 8 | 2012-03-04 |
+----+------------+
1 row in set (0.00 sec)