1

I'm trying to do multiple inserts on a MySQL db like this:

p = 1
orglist = buildjson(buildorgs(p, p))
while (orglist is not None):
    for org in orglist:
        sid = org['sid']
        try:
            sql = "INSERT INTO `Orgs` (`sid`) VALUES (\"{0}\");".format(sid)
            cursor.execute(sql)
            print("Added {0}".format(org['title']))
        except Exception as bug:
            print(bug)
    conn.commit()
    conn.close()
    p += 1
    orglist = buildjson(buildorgs(p, p))

However I keep getting a bunch of 2055: Lost connection to MySQL server at 'localhost:3306', system error: 9 Bad file descriptor

How can I correctly do multiple inserts at once so I don't have to commit after every single insert. Also, can i only do conn.close()after the while loop or is it better to keep it where it is?

1 Answer 1

3

This may be related to this question and/or this question. A couple ideas from the answers to those questions which you might try:

  1. Try closing the cursor before closing the connection (cursor.close() before conn.close(); I don't know if you should close the cursor before or after conn.commit(), so try both.)
  2. If you're using the Oracle MySQL connector, try using PyMySQL instead; several people said that that fixed this problem for them.
Sign up to request clarification or add additional context in comments.

3 Comments

Switching libraries gave me: Traceback (most recent call last): File "grabber.py", line 57, in <module> poporgs() File "grabber.py", line 42, in poporgs conn.commit() File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 718, in commit self._execute_command(COMMAND.COM_QUERY, "COMMIT") File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 956, in _execute_command raise err.InterfaceError("(0, '')") pymysql.err.InterfaceError: (0, '')
I see you just accepted this answer, but your last comment suggests that it hadn't been working for you. What changed? You should probably mention (in a comment, if nothing else) what you did differently that made this answer work for you, so that anyone else who finds this question later will know.
I closed the cursor before closing the connection and I removed conn.close() from within the while loop to the very end of the code. Not sure which one of these fixed it but it started working. Also, thanks for the tip, I tend to forget commenting on what actually fixed the issue later on :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.