Форум сайта python.su
0
Приветствую!
Подскажите, пожалуйста, как надо работать с кавычками.
Код:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import MySQLdb
# DB connect
db = MySQLdb.connect(host="127.0.0.1", user="user", passwd="pass", db="testdb", charset='utf8')
cursor = db.cursor()
content = "==='==="
sql = """INSERT INTO test( content ) VALUES ( %(content)s )""" % { 'content':content }
cursor.execute(sql)
db.commit()
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version for the right syntax to use
near '==='=== )' at line 1")
CREATE TABLE IF NOT EXISTS `test` (
`content` varchar(256) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Офлайн
0
драйвер позаботится, если подстановку делать правильно:
cursor.execute("INSERT INTO test (content) VALUES (%(content)s)", { 'content': content })cursor.execute("INSERT INTO test (content) VALUES (%s)", [content])Офлайн
0
То есть в моём случае до драйвера не доходило - я пихал аргументы в строку до него.
Спасибо за помощь!
Офлайн
0
Метод форматирования строк…
Например:
o = 'orange' p = 'potatoes' pep ='pepper' val = 'fruit {0}, vegetable \{{1}, {2}\}' .format(o, p, pep) print val
Офлайн
857
>>> o = 'orange' >>> p = 'potatoes' >>> pep ='pepper' >>> val = 'fruit {0}, vegetable {{{1}, {2}}}' .format(o, p, pep) >>> print val fruit orange, vegetable {potatoes, pepper} >>>
Офлайн
0
Спасибо!
А как в таком случае?:
import json from collections import OrderedDict city = 1 json_arg = json.dumps(OrderedDict([ ("celebration_type","party"), ("town_id", "???? city")], )) print json_arg
Офлайн
173
Seganapa
Мне нужно чтобы значение переменной city подставлялось в “town_id” в кавычках…
... ("town_id", str(city)) ...
print '"%s"' % city
Офлайн