Andrew Feather
Andrew Feather

Reputation: 183

Inserting into Postgres Database from SQLAlchemy

I'm trying to enter a value from an HTML form into a postgresql database, and I'm getting a 500 error. It works fine if I manually enter the values into the program like this...

@app.route('/add', methods=['POST'])
def add():
  name = request.form['name']
  employer_id = random.random()%100000;
  g.conn.execute("INSERT INTO employers(employer_id,name) VALUES ('C005329438','Twitter')")
  return redirect('/')

But I get an error every time I send it the value from the form like this

@app.route('/add', methods=['POST'])
def add():
  name = request.form['name']
  employer_id = random.random()%100000;
  g.conn.execute("INSERT INTO employers(employer_id,name) VALUES (%d,%s)", employer_id, name)
  return redirect('/')

Upvotes: 0

Views: 2164

Answers (1)

Ilja Everilä
Ilja Everilä

Reputation: 53017

g.conn.execute("INSERT INTO employers(employer_id,name) VALUES (%d,%s)", employer_id, name)

should probably be:

from sqlalchemy import text

g.conn.execute(text("INSERT INTO employers(employer_id,name) VALUES (:id, :name)"),
               {"id": str(employer_id), "name": name})

text() provides backend neutral support for bind parameters.

Your employer id attribute seems to be a text type too according to your successful query, so I added the str() wrapping.

Upvotes: 3

Related Questions