Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #75908 > unrolled thread

Re: Newbie needing some help

Started byMark Lawrence <breamoreboy@yahoo.co.uk>
First post2014-08-08 22:54 +0100
Last post2014-08-08 22:54 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Newbie needing some help Mark Lawrence <breamoreboy@yahoo.co.uk> - 2014-08-08 22:54 +0100

#75908 — Re: Newbie needing some help

FromMark Lawrence <breamoreboy@yahoo.co.uk>
Date2014-08-08 22:54 +0100
SubjectRe: Newbie needing some help
Message-ID<mailman.12764.1407534891.18130.python-list@python.org>
On 08/08/2014 20:07, Matt Smith wrote:
> I am trying to write a program that will loop through a text file and
> delete rows in a mysql database.
>
> It seemingly runs but I don't see anything getting deleted in the db.
> Is there anything apparent that I am missing?
>
> This is the code:
> #!/usr/bin/python
> import mysql.connector
> #
> f=open('/home/smithm/email-list.txt', 'r')

The modern idiom is:-

with open(...) as f: but that doesn't matter here.

> for line in f:
>          #<do something with line>
>          # Open database connection
>          db = mysql.connector.connect(user="xx", password="xx",
> host="localhost", database="xx")
>
>          # prepare a cursor object using cursor() method
>          cursor = db.cursor()

Are you aware that you're connecting to your db and setting up the 
cursor in every iteration of the loop?

>
>          # Prepare SQL query to DELETE required records
>          sql = "DELETE FROM tblc_users WHERE user_email=%s, % (line)"
>          try:
>            # Execute the SQL command
>            cursor.execute(sql)
>            # Commit your changes in the database
>            db.commit()
>          except:

This bare except is masking every possible thing that can go wrong. 
Strip it out and I expect you'll find your mistake in seconds.  Once 
you've corrected your code add back in the bare minimum number of 
exceptions that you really should catch.

>            # Rollback in case there is any error
>            db.rollback()
>
>          # disconnect from server
>          db.close()
>
> --
> Matthew Smith
>

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web