Menu

Silent duplicate insertion

Help
2005-09-29
2012-09-19
  • Seung Won Jun

    Seung Won Jun - 2005-09-29

    When I insert a duplicate item that the table doesn't allow, cursor.execute("INSERT ...") doesn't raise any exceptions. Instead, the subsequent cursor.fetchone() shows

    (1062, "Duplicate entry 'xxx' for key 2")

    However, I'd like the duplicate insertion to raise an exception, as it will ease my coding. Any solutions suggested will be appreciated.

     
    • Andy Dustman

      Andy Dustman - 2005-09-29

      Post a code example, and include all the versions of things you are using, especially for Python, MySQL, and MySQLdb. Your table type/engine may be relevant, as well as your table schema.

      Your post confuses me because if your INSERT is trying to add a duplicate item, you should have IntegrityError raised, with a value that probably looks like (1062, "Duplicate entry 'xxx' for key 2"). Furthermore, an INSERT will never return any rows, so there is no need to call cursor.fetchone(). Also, I am pretty sure it is impossible for any of the .fetchXXX() methods to return an error like this if you are using the standard cursor, because they do not interact with the C API at all. SSCursor does interact with the C API, but I am pretty sure it is impossible for it to raise this error. By this I mean, .execute() is the only thing capable of raising this particular exception.

       
    • Seung Won Jun

      Seung Won Jun - 2005-09-29

      You are right. An exception is raised and caught. I thought "print record" at the end was printing the line, but in fact it was printed by "print e". I had expected that some traceback message would be printed if it was an error :) Thanks alot.

      --

      ! /usr/bin/env python # 2.4

      import MySQLdb # 1.2.0 (MySQL: 4.1.10a)

      try:
      conn = MySQLdb.connect(host="localhost", user="root", db="rss",
      read_default_file="~/.my.cnf")
      cursor = conn.cursor()
      cursor.execute("""INSERT INTO feed (title) VALUES ("xxx")""")
      results = cursor.fetchall()
      except MySQLdb.MySQLError, e:
      print e

      for record in results:
      print record

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.