2012-12-05 20 views
1

當我嘗試使用%的語法與SQLAlchemy的和SQLite我得到一個錯誤。 PostgreSQL的語法相同工作正常:問題與%s與SQLAlchemy的核心和SQLite

import sqlalchemy 
e = sqlalchemy.create_engine('sqlite:////tmp/x.db?timeout=120000') 
e.execute('select * from people where name = %s;', 'joe').fetchall() 

我得到這個:

Traceback (most recent call last): 
    File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 1396, in _cursor_execute 
    context) 
    File "/usr/lib/python3/dist-packages/sqlalchemy/engine/default.py", line 301, in do_execute 
    cursor.execute(statement, parameters) 
sqlite3.OperationalError: near "%": syntax error 

The above exception was the direct cause of the following exception: 

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 1790, in execute 
    return connection.execute(statement, *multiparams, **params) 
    File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 1191, in execute 
    params) 
    File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 1287, in _execute_text 
    return self.__execute_context(context) 
    File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 1302, in __execute_context 
    context.parameters[0], context=context) 
    File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 1403, in _cursor_execute 
    context) 
    File "/usr/lib/python3/dist-packages/sqlalchemy/engine/base.py", line 1360, in _handle_dbapi_exception 
    from e 
sqlalchemy.exc.OperationalError: (OperationalError) near "%": syntax error 'select * from people where name = %s;' ('joe',) 
>>> 

再次,Postgres的同樣的事情返回一個列表或行。 這是一個錯誤? 還是預計?

回答

3

有一個小問題字符串中'select * from people where name = %s;', 'joe'

%s格式用於字符串格式化,%s是字符串後期待%some sort Data to be replaced

你應該刪除,%s;', 'joe'並添加%到得到

In [10]: 'select * from people where name = %s;' %'joe' 
Out[10]: 'select * from people where name = joe;' 
+0

是的,沒有這個,字符串替換不會發生在Python中。 –

+2

不,它不起作用。我沒有試圖使用python替代,但sqlalchemy語法。它適用於postgresql,但不適用於sqlite。 –

+0

@ user1014841:對於sqlalchemy,您需要將'%'標誌轉義爲'%%' – avasal

0

我通過使用問號語法來解決它:

e.execute('select * from people where name = ?;', 'joe').fetchall() 

這適用於sqlite 和postgres

the chapter about sqlalchemy in the Pylon's book

不同的數據庫使用不同的標記(被稱爲PARAM樣式)標記,你傳遞給執行變量()應插入。上面的例子使用了SQLite,它使用?作爲參數樣式,但如果您嘗試使用MySQL或PostgreSQL,則需要使用%s作爲參數樣式。 SQL將看起來像這樣

正確的答案是用戶sqlalchemy「文本」(請參閱​​我的其他答案)。

+0

與您的原始文章不一樣嗎?你的意思是('select * from people where name =?;','joe')也許? –

+1

你是對的,我複製並粘貼從我的原始文章沒有修復它。我現在編輯它。 –

0

正確的答案是van在他的回答another of my posts。解決方案是使用sqlalchemy "text"。這適用於SQLite和PostgreSQL(並且我假設其他服務器也是如此),因此您可以編寫一次並將其用於不同的數據庫服務器(只要您保留SQL通用當然)。