0

I'm inserting data into SQLite using Python

database_tasks.bookId is a class variable

def insert(self, conn,dbname, name, writer='none'):
        c = conn.cursor()

        if dbname == "Book_database":            
            database_tasks.bookId += 1
            sql= "INSERT INTO Book_database VALUES(" + database_tasks.bookId + "," + name + "," + writer + ")"

        else:
            database_tasks.studentId += 1
            sql= "INSERT INTO Student VALUES("+ database_tasks.studentId + "," + name + ")"

        c.execute(sql)
        conn.commit()        
        return None

I'm getting an error with Insert command.

sql= "INSERT INTO Book_database VALUES(" + database_tasks.bookId + "," + name + "," + writer + ")"

TypeError: can only concatenate str (not "int") to str

3 Answers 3

1

You should never build a query string including values to insert that way but used parameterized queries. It is an anti-pattern that has been used for decades to build SQL injection attacks. You should use:

    if dbname == "Book_database":            
        database_tasks.bookId += 1
        c.execute("INSERT INTO Book_database VALUES(?,?,?)",
                  (database_tasks.bookId, name, writer))

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

Comments

0
  • it looks like your bookId is int. Cast it to str before combining.
sql= "INSERT INTO Book_database VALUES(" + str(database_tasks.bookId) + "," + name + "," + writer + ")"

Comments

0

The error is fairly self explanatory - you are trying to concatenate an integer to a string.

my assumption is that database_tasks.studentId is an int, so changing your query to

sql= "INSERT INTO Book_database VALUES(" + str(database_tasks.bookId) + "," + name + "," + writer + ")"

would fix this, however be aware that if this is public facing, it would be very easy to exploit this, I'd recommend fully validating input, or changing your approach to this problem.

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.