通过python插入MySQL语句

2024-10-01 22:35:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个python脚本,它将视频url和时间添加到DB中的videopost表中。这是我在python的第三个脚本。我还在学习。另外,请告诉我如何缩短这个脚本的执行时间。在

代码:

  #!/usr/bin/python
  import MySQLdb
  import sys

  db = MySQLdb.connect (host = "host.com", user="myusername",passwd="pass", db = "dbname")

  cursor = db.cursor ()
  db.query("SELECT now()")
  result = db.use_result()
  time= str("%s" % \
      result.fetch_row()[0])
  print time
  db.close()
  cursor =db.cursor()
  vidurl = raw_input("Enter the URL to the video:")
  print vidurl

  cursor.execute ("""INSERT INTO videopost(vidurl, time) VALUES (%s, %s)""", (vidurl,time))
  db.commit()
  db.close()

我输入的错误是

^{pr2}$

谢谢你的帮助。对于寻求解决方案的人,我将更正如下:

  cursor.execute("SELECT now()")
  result = cursor.fetchall()
  time= str("%s" % \
        result[0])
  print time
  vidurl = raw_input("Enter the URL to the video:")
  print vidurl

Tags: theimport脚本hostdbtime时间result
2条回答

您正在关闭连接,然后尝试获取光标:

db.close()
cursor =db.cursor()

去掉第一行,一切都会好起来的。在

为什么不使用:

cursor.execute ("""INSERT INTO videopost(vidurl, time) VALUES (%s, NOW())""", (vidurl,))

相关问题 更多 >

    热门问题