Learn how to store data in Anvil’s hosted database system
Anvil provides a robust Python-based database system built on top of PostgreSQL.
Follow this quickstart to create a data table in your app’s default database, get your app to store data in it, and read the data back.
Anvil provides a robust Python-based database system built on top of PostgreSQL called Data Tables.
Follow this quickstart to create a database, get your app to store data in it, and read the data back.
Create an app
Log in to Anvil and click ‘New Blank App’. Choose the Material Design theme.
Add the Data Tables Service
In the App Browser, click the + next to Services.
You’ll see a list of available services and integrations. Click on Data Tables.
Create a table
Click ‘Add A Table’ and name it square_numbers
.
Navigate to “Data” in the Sidebar Menu and click “+ Add Table”.
Change the name to be square_numbers
.
Add columns
Click New Column, and in the menu that pops up, name the new column base_number
. Change the Column Type to “Number”.
Then add another Number column named squared
.
Make the table client-writable
In the bar above the columns, there are some controls relating to this table.
Use the dropdown menu that says ‘Client code’ to select ‘Client code can search, edit and delete’. This gives our client-side Forms permission to read from and write to this table.
Write to the database from Python code
Under Forms in the App Browser, select Form1.
Click on the ‘Code’ tab to see the Python code for Form1
.
You will see a few lines of pre-written code. Your Form is represented as a class called Form1. It currently has
only one method, the __init__
method.
At the top of the file, import the random
module:
import random
And at the end of the __init__
method, write these lines:
base_number = random.randint(1, 100)
app_tables.square_numbers.add_row(base_number=base_number, squared=base_number**2)
Run your app
Now click the ‘Run’ button at the top of the screen.
Stop the app and look back at the Data Tables service. Your table now contains some data.
Stop the app and look back at the Data service. Your table now contains some data.
Run your app a few times to get some more data in the database.
Read from the database
Go back to the Code View for Form1 and add these lines to the end of the __init__
method:
for row in app_tables.square_numbers.search():
print(f"{row['base_number']} squared is {row['squared']}")
Run your app again and you’ll get the contents of your table printed to the Output Panel.
Run your app again and you’ll get the contents of your table printed to the App Console.
Copy the example app
Click on the button below to clone a finished version of this app into your account.
Next up
Want more depth on this subject?
Read more about databases.
Read more about Data Tables.
Want another quickstart?
Every quickstart is on the Quickstarts page.
Do you still have questions?
Our Community Forum is full of helpful information and Anvil experts.