我有一个用Python创建的MySQL表
+--------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| consensus | char(40) | NO | | NULL | |
| identityb32 | char(40) | NO | | NULL | |
| pubdate | char(40) | NO | | NULL | |
| dirport | char(6) | NO | | NULL | |
| ip | char(40) | NO | | NULL | |
| orport | char(40) | NO | | NULL | |
| identityhash | char(40) | NO | | NULL | |
| nick | char(40) | NO | | NULL | |
| version | char(40) | NO | | NULL | |
| flags | varchar(500) | NO | | NULL | |
| identity | char(40) | NO | | NULL | |
| digest | char(40) | NO | | NULL | |
| pubtime | char(40) | NO | | NULL | |
+--------------+--------------+------+-----+---------+-------+
13 rows in set (0.00 sec)
一切都很好,接受一个小问题。
对于我的flags
字段,我需要添加的值采用以下格式:
['Exit', 'Fast', 'Guard', 'HSDir', 'Named', 'Running', 'Stable', 'V2Dir', 'Valid']
我无法将这些值添加到表中。为了将字段的所有标志值添加到标志字段,我需要做什么?
PYTHON代码:
format = """','"""
c = 0
# Prepare SQL query to INSERT a record into the database.
sql = """INSERT INTO """ + onion_Add +"""(consensus, identityb32, pubdate, dirport, ip, orport, identityhash, nick, version, flags, identity, digest, pubtime)
VALUES ('""" +consensus.consensus_name + format + identityb32[c] + format + pubdate[c] + format + dirport[c] + format + ip[c] + format + orport[c] + format + identityhash[c] + format + nick[c] + format + version[c] + format + flags + format + identity[c] + format + digest[c] + format + pubtime[c] + """')"""
try:
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
db.commit()
except:
# Rollback in case there is any error
db.rollback()
print "adding to db error"
# disconnect from server
db.close()
答案 0 :(得分:0)
您可能会发现让MySQLdb为您构建语句更容易,更安全:
sql_fmt = 'INSERT INTO %s (consensus, identityb32, pubdate, dirport, ip, orport, identityhash, nick, version, flags, identity, digest, pubtime) VALUES (' + ', '.join(['%s']*14) + ')'
...
cursor.execute(sql_fmt, (onion_Add, consensus.consensus_name,
identityb32[c], pubdate[c], dirport[c],
ip[c], orport[c], identityhash[c], nick[c],
version[c], ','.join(flags), identity[c],
digest[c], pubtime[c])
)