【问题标题】:Multiple sql statement in pythonpython中的多个sql语句
【发布时间】:2018-09-27 21:05:45
【问题描述】:

我尝试了多个来自 mysql 的更新数据。这是我的代码:

que = "select id_pl from datapl
db = MySQLdb.connect("localhost", "root", "", "tuongdata")
cur = db.cursor()
cur.execute(que)
pl = cur.fetchall()
cur.close()
pl = [ i[0] for i in pl ]
di = './newsdata/'
for i in pl:
    lin = di + i + '/'
    numb = len([name for name in os.listdir(str(lin)) if os.path.isfile(os.path.join(lin, name))])
    qq = "update datapl set num = " + str(numb) + " where id_pl = " + str(i)
    cur = db.cursor()
    cur.execute(qq)
    cur.close()
    #print qq
db.close()

但它不起作用,我不知道为什么:(

【问题讨论】:

  • 您需要在第一行末尾加上一个双引号 "

标签: python python-2.7 mysql-python


【解决方案1】:

您似乎忘记在关闭连接之前提交更改。如果没有提交,数据库中将看不到任何更改。

que = "select id_pl from datapl"
db = MySQLdb.connect("localhost", "root", "", "tuongdata")
cur = db.cursor()
cur.execute(que)
pl = cur.fetchall()
cur.close()
pl = [ i[0] for i in pl ]
di = './newsdata/'
for i in pl:
    lin = di + i + '/'
    numb = len([name for name in os.listdir(str(lin)) if os.path.isfile(os.path.join(lin, name))])
    qq = "update datapl set num = " + str(numb) + " where id_pl = " + str(i)
    cur = db.cursor()
    cur.execute(qq)
    cur.close()
    db.commit() # <---- Commits after each execution.
    #print qq
db.close()

【讨论】:

  • 是的,但是创建这样的查询也是不好的做法,因为它很容易被 SQL 注入
猜你喜欢
  • 2012-05-05
  • 2019-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多