3

I am trying to build a money spending monitor and am starting with db. i have a script for building the table:

def create_table(name):
    conn = db.connect(dbname='Money_Tracker' ,user="",password="",host="",port="")
    cur = conn.cursor()
    cur.execute(f"CREATE TABLE IF NOT EXISTS {name}(ID SERIAL PRIMARY KEY ,F_Name VARCHAR, L_Name VARCHAR, Expense INT, Category VARCHAR  )")
    conn.commit()
    conn.close()

and created a table

create_table("money_spent")

secondly i built a function in order to insert data into the table:

def add_money_spent(Firstname, Lastname, Amount, Cat):
    conn = db.connect(dbname='Money_Tracker' ,user="",password="",host="",port="")
    cur = conn.cursor()
    cur.execute("INSERT INTO money_spent VALUES(%s, %s, %s, %s)",(Firstname,Lastname,Amount,Cat))
    conn.close()

and am tring to use it like this:

add_money_spent("Michael","Ben-Haym",15,"Cofee")

when i run the code i get the error sycopg2.errors.InvalidTextRepresentation: invalid input syntax for type integer: "Cofee" LINE 1: ... INTO money_spent VALUES(15, 'Michael', 'Ben-Haym', 'Cofee')
it seems the code thinks cofee should be an integer even though i specified in the table that categories should be varchar
can someone please explain to me how i can fix this?
thanks :)

4
  • Can you try instead: cur.execute("INSERT INTO money_spent (F_name, L_Name, Expense, Category) VALUES(%s, %s, %s, %s)",(Firstname,Lastname,Amount,Cat))? Commented Jan 12, 2020 at 16:10
  • now i don't get an error but it also doesn't get into the db, it stays empty Commented Jan 12, 2020 at 16:18
  • Ok, do conn.commit() before you close the connection. Commented Jan 12, 2020 at 16:19
  • omg i cant belive i forgot the commit i love you thanks it works now Commented Jan 12, 2020 at 16:21

1 Answer 1

2

It appears that the column order is random. So you must specify it:

cur.execute("""INSERT INTO money_spent (F_name, L_Name, Expense, Category) 
               VALUES(%s, %s, %s, %s);""",(Firstname,Lastname,Amount,Cat))

Then please make sure to commit your changes with:

conn.commit()

Before you close the connection.

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.