mar*_*oss 2 python string-concatenation
我来自PHP背景.在编写SQL查询时,我倾向于做这样的事情:
$query = '
SELECT
*
FROM `table` AS t
WHERE
t.`categoryID` = '.$categoryID.'
';
if(!empty($recordID))
{
$query .= '
AND t.`recordID` = '.$recordID.'
';
}
$data = $db->fetchAll($query);
Run Code Online (Sandbox Code Playgroud)
在Python中执行此操作的最佳/最有效方法是什么?
有很多方法可以使用Python实现它.最简单的方法是使用格式字符串语法或Template对象.
格式字符串语法的优点是您不需要使用其他对象.例:
query = "SELECT * FROM `table` AS t WHERE t.`categoryID`={}".format(category_id)
if record_id:
query += " AND t.`recordID`={}".format(record_id)
Run Code Online (Sandbox Code Playgroud)
虽然大多数情况下数据库Python包装器会让你更安全(防止SQL注入):
cursor.execute("UPDATE Writers SET Name = %s WHERE Id = %s", ("Leo Tolstoy", "1"))
Run Code Online (Sandbox Code Playgroud)
您可能对以下链接感兴趣:
以下是它如何适用于Postgresql:
ps = db.prepare("SELECT * FROM information_schema.tables WHERE table_name = $1 LIMIT $2")
ps("tables", 1)
Run Code Online (Sandbox Code Playgroud)
使用python DB-API参数替换:
symbol = 'IBM'
# Do this
t = (symbol,)
c.execute('select * from stocks where symbol=?', t)
# Larger example
for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00),
]:
c.execute('insert into stocks values (?,?,?,?,?)', t)
Run Code Online (Sandbox Code Playgroud)
来自:http : //docs.python.org/library/sqlite3.html
| 归档时间: |
|
| 查看次数: |
11777 次 |
| 最近记录: |