-1

I am writing a script in python to listen to the twitter streaming api which will track specific keywords and insert them in mysql database using MySQLdb. I am not sure which way to choose:

  1. For each incoming tweet, open a db connection, insert to db, then close the connection.
  2. Open a db connection and execute insert command for incoming tweets and not closing the connection at all.

I think the script will receive 1-10 tweets per second.

PHA
  • 1,588
  • 5
  • 18
  • 37
  • check first answer here: http://stackoverflow.com/questions/880885/is-closing-the-mysql-connection-important in summary, if you are not doing any processing besides saving to the database, don't close the connection – Lucas Sep 17 '15 at 12:27

1 Answers1

0

It kind of depends on how your script is supposed to be run, but it should close the connection at some point - at least once when the process dies. Assuming it's a long-running process (daemon etc), the simplest strategy would be to use a "with" block to ensure the connection is closed, ie:

with MySQLdb.connect(**kw) as db:
    while some_condition():
        do_stuff_with(db)

but you'll probably need something a bit more involved since MySQL tends to close idle connections by itself

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118