2 qq 15120815 qq_15120815 于 2015.06.14 12:01 提问

python把变量如何写入mysql

GAME_ID = s["resultSets"][0]["rowSet"][i][0]

TEAM_ID = s["resultSets"][0]["rowSet"][i][1]
PLAYER_NAME = s["resultSets"][0]["rowSet"][i][5]

db = MySQLdb.connect("localhost","root","199536abc","test")

cursor = db.cursor()
sql = """INSERT INTO PLAYER(GAME_ID,TEAM_ID,NAME)
VALUES (GAME_ID,TEAM_ID,PLAYER_NAME)"""

try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# Rollback in case there is any error
db.rollback()

                现在的问题是sql语句里values后面括号里的三个不是之前定义的GAME_ID,TEAM_ID,PLAYER_NAME,
                只能写固定值“21212”,1212,“nick”这样的
                求解

2个回答

oyljerry
oyljerry   Ds   Rxr 2015.06.14 23:12

你需要格式化字符串,用format来组合你的sql语句,然后再执行。

devmiao
devmiao   Ds   Rxr 2015.06.14 12:41

sql = "INSERT INTO PLAYER(GAME_ID,TEAM_ID,NAME) VALUES (" + GAME_ID + "," + TEAM_ID + ",'" + PLAYER_NAME + ")'"
如果GAME_ID是字符串,前后加上引号

qq_15120815
qq_15120815 GAME_ID 和PLAYER_NAME是char ,TEAM_IN 是INT
2 年多之前 回复
qq_15120815
qq_15120815 GAME_ID 和PLAYER_NAME是char ,TEAM_IN 是INT
2 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片