Hello!
I have this funtion to delete a record from a MySQL table:

def delUser(): #Delete user
	#Ask for user to delete
	Username = raw_input('Which user would you like to delete? ')
	#Delete user
	delUser = '''DELETE FROM Users WHERE Username = %s'''
	cursor.execute(delUser,(Username))
	db.commit()

The problem is that it makes nothing if the selected user (Username) does not exist. In case the user does not exist, I would like the function to print an error (something like "User does not exist. Try again", and go back to the raw input line. How can I do it?
Cheers!

Dani

Dani AI

Generated

Short answer: either run the DELETE and check how many rows were affected, or SELECT first to verify the user exists, then loop until you get a positive result. 's SELECT-first idea is fine for friendly prompts; was right that the cursor contains useful state (use cursor.rowcount). Also fix the parameter passing — cursor.execute(sql, (username,)) needs a tuple (note the trailing comma).

Example using rowcount (cleanup, commit on success, reprompt on zero rows):

def delete_user_loop(cursor, db):
    try:
        while True:
            username = raw_input('Which user would you like to delete? ').strip()
            if not username:
                print 'Please enter a username.'
                continue

            cursor.execute('DELETE FROM Users WHERE Username = %s LIMIT 1', (username,))
            if cursor.rowcount == 0:
                print 'User does not exist. Try again.'
                continue

            db.commit()
            print 'Deleted user:', username
            break
    except KeyboardInterrupt:
        print '\nCancelled.'
    except Exception as e:
        db.rollback()
        print 'Database error:', e

Notes and troubleshooting:

  • Use LIMIT 1 if Username is not guaranteed unique and you want only one row removed.
  • cursor.rowcount gives the number of rows affected by the DELETE; check it immediately after execute.
  • Pass parameters as a tuple or list — ('name',) or ['name'] — not (name) which is just the string in parentheses.
  • Consider a SELECT/EXISTS approach if you need to show extra info about the user before deleting. For UIs that must be atomic, DELETE+rowcount is simpler and avoids an extra round-trip.
  • Watch collation/case-sensitivity on the Username column, autocommit settings, and always rollback on exceptions to avoid leaving transactions open.

Recommended Answers

All 2 Replies

You can do a select first to see if it exits, and delete thereafter if exists, or give error message if it doesn't.

if you are using mysqldb, the cursor object should contain some information about the query/delete, check it out

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.