通过python插入语句MySQL

时间:2012-12-16 08:04:35

标签: python

我正在尝试创建一个python脚本,在DB中为我的视频表添加视频网址和时间。这是我在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()

我遇到的错误是

  File "vidup.py", line 28, in <module>
  cursor.execute ("""INSERT INTO videopost(vidurl, time) VALUES (%s, %s)""", (vidurl,time))
  File "/usr/local/lib/python2.6/site-packages/MySQL_python-1.2.3-py2.6-freebsd-8.2-RELEASE-amd64.egg/MySQLdb/cursors.py", line 155, in execute _mysql_exceptions.InterfaceError: (0, '')

非常感谢你的帮助。对于寻找解决方案的人,我发布以下更正:

  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

2 个答案:

答案 0 :(得分:1)

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

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

删除第一行,一切都应该有效。

答案 1 :(得分:1)

为什么不使用:

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