1

This is my code :

import sqlite3

def delete_product(data):
    with sqlite3.connect("main.db") as db:
        cursor = db.cursor()
        sql = "delete from Products where Name=?"
        if cursor.rowcount <= 0:
            print("The product {0} does not exist" .format(name))
        if cursor.rowcount > 0:
            cursor.execute(sql,data)
            db.commit()
            print("The product {0} has been delted successfully" .format(name))

if __name__ == "__main__":
    name=input("Enter the name of the product you want to delete: >>")
    data=(name,)
    delete_product(data)

I want to check if the name actually exists in the database or not if it exists then delete it. if it doen't exist then print out an error. can anyone help me spot where the problem is

5
  • You should post full error message. It will help identify the problem. Commented Dec 21, 2016 at 21:44
  • You should probably specify what output do you get and why it is unexpected. Commented Dec 21, 2016 at 21:45
  • @beeftendon there is no error message it's just the checking if exists bit doesn't work Commented Dec 21, 2016 at 21:45
  • @YevhenKuzmovych there is no output it just tells me the product doesnt exist even though it does Commented Dec 21, 2016 at 21:47
  • There is no need for any of this. Just execute "delete from Products where Name=?". If it exists, it's deleted. If it doesn't, nothing is deleted. Commented Dec 21, 2016 at 21:58

1 Answer 1

1

Regarding cursors, the Python sqlite3 documentation states:

As required by the Python DB API Spec, the rowcount attribute “is -1 in case no executeXX() has been performed on the cursor...

You define the cursor variable without performing any execute command. Thus, cursor.rowcount will be -1, and cursor.rowcount <= 0 will always be true.

Maybe you intended to place the line

cursor.execute(sql,data)

before the first cursor.rowcount check?

Sign up to request clarification or add additional context in comments.

Comments

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.