Phil
Phil

Reputation: 3

How to get the data object of a newly inserted data row and flask-mysqldb?

I have work in Perl where I am able to get the newly created data object ID by passing the result back to a variable. For example:

my $data_obj = $schema->resultset('PersonTable')->create(\%psw_rec_hash);

Where the $data_obj contains the primary key's column value.

I want to be able to do the same thing using Python 3.7, Flask and flask-mysqldb, but without having to do another query. I want to be able to use the specific record's primary key column value for another method.

Python and flask-mysqldb inserts data like so:

query = "INSERT INTO PersonTable (fname, mname, lname) VALUES('Phil','','Vil')
cursor = db.connection.cursor()
cursor.execute(query)
db.connection.commit()
cursor.close()

The PersonTable has a primary key column called, id. So, the newly inserted data row would look like: 23, 'Phil', 'Vil'

Because there are 22 rows of data before the last inserted data, I don't want to perform a search for the data, because there could be more than one entry with the same data. However, all I want the most recent data row.

Can I do something similar to Perl with python 3.7 and flask-mysqldb?

Upvotes: 0

Views: 551

Answers (1)

user3832673
user3832673

Reputation: 354

You may want to consider the Flask-SQLAlchemy package to help you with this.

Although the syntax is going to be slightly different from Perl, what you can do is, when you create the model object, you can set it to a variable. Then, when you either flush or commit on the Database session, you can pull up your primary key attribute on that model object you had created (whether it's "id" or something else), and use it as needed.

SQLAlchemy supports MySQL, as well as several other relational databases. In addition, it is able to help prevent SQL injection attacks so long as you use model objects and add/delete them to your database session, as opposed to straight SQL commands.

Upvotes: 1

Related Questions