Skip to content Skip to sidebar Skip to footer

Adding Postgresql To My Heroku App - Issues With Syntax Crashing Queries?

I'm teaching myself Python, Flask, and adding Postgresql to the mix. I recently deployed my first app on Heroku that didn't use database at all, but now I'm wanting to add on func

Solution 1:

User is a reserved word in postgresql and is escaped by enclosing it with "" See https://stackoverflow.com/a/7651432. In contrast to mysql where the escaping characters are backticks.

You also try to insert into a column named Final_Ratio but define a column Final_Gearing. For testing I#m also dropping and recreating the table each run. The fixed code:

import psycopg2

# connect to remote Heroku Postgres DB
pgdb = psycopg2.connect(
   host='localhost',
   user='test',
   password='test',
   port='5432',
   database='test_stackoverflow'
   )

pgcursor = pgdb.cursor()

# verify I've got my credentials in correctlydefcheck_connection():
   pgcursor.execute("select version()")
   data = pgcursor.fetchone()
   print("Connection established to: ", data)

defcreate_table():
   sql = '''CREATE TABLE estimation_data 
   ("User" text PRIMARY KEY,
    Motor_kV integer,
     Batt_Volt decimal,
      Pinion integer,
       Spur integer,
        Final_Gearing decimal,
         Wheel_Rad decimal);'''
   pgcursor.execute(sql)
   pgdb.commit()

defdrop_table():
   sql = "DROP TABLE IF EXISTS estimation_data;"
   pgcursor.execute(sql)
   pgdb.commit()



defpg_add_data(sql,val):
   pgcursor.executemany(sql, val)
   pgdb.commit()


check_connection()
drop_table()
create_table()

pgsql = '''INSERT INTO estimation_data 
   ("User", Motor_kV, Batt_Volt, Pinion, Spur, Final_Gearing, Wheel_Rad) 
   VALUES (%s, %s, %s, %s, %s, %s, %s);'''
pgval = [
      ('204.210.165.122', 2400, 16.8, 16, 54, 3.92, 2.5),
      ('204.210.165.123', 3500, 12.6, 16, 54, 3.92, 2.5),
      ('204.210.165.124', 4200, 8.4, 12, 54, 3.92, 2.5)]
pg_add_data(pgsql, pgval)

While it is good to learn the basics for a production site I would strongly recommend using a high level library like SQLalchemy.

Post a Comment for "Adding Postgresql To My Heroku App - Issues With Syntax Crashing Queries?"