[英]String formatting on SQL insert using dict
The following is how I usually add in params in MySQLdb
: 以下是我通常在
MySQLdb
添加参数的MySQLdb
:
cursor.execute('INSERT INTO main_territory (code, name) VALUES (%s, %s)', (item[0], item[1]))
Is there a way to make the string formatting more intuitive? 有没有一种方法可以使字符串格式更直观? For example, if I have 50 args in the
INSERT
. 例如,如果我在
INSERT
有50个参数。 Something like: 就像是:
cursor.execute('''INSET INTO main_territory (code, name) VALUES ({code}, {name})''',
{code=item[0], name=item[1}
)
This depends on the database driver. 这取决于数据库驱动程序。 Usually, if positional arguments (
%s
) are supported, then named arguments could be to, using the %(name)s
format: 通常,如果支持位置参数(
%s
),则可以使用%(name)s
格式指定命名参数:
cursor.execute(
'''INSERT INTO main_territory (code, name) VALUES (%(code)s, %(name)s)''',
{'code': item[0], 'name': item[1]})
The parameter values then are passed in as a dictionary. 然后,将参数值作为字典传递。
The most commonly used MySQL database adapter, MySQLdb supports this style. 最常用的MySQL数据库适配器MySQLdb支持此样式。
Other database adapters use ?
其他数据库适配器使用
?
and :name
as the positional and named arguments; 和
:name
作为位置和命名参数; you can query the style used with the paramstyle
attribute on the module: 您可以查询与模块上的
paramstyle
属性一起使用的样式:
>>> import MySQLdb
>>> MySQLdb.paramstyle
'format'
but because most drivers support both positional and named styles, they usually just name one ( 'format'
or 'qmark'
) while also supporting the named variants. 但是由于大多数驱动程序都支持位置样式和命名样式,因此它们通常只命名一个(
'format'
或'qmark'
),同时还支持命名变体。 Always consult the documentation to verify this. 请始终查阅文档以进行验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.