Live Chat

We'll need to share your messages (and your email address if you're logged in) with our live chat provider, Drift. Here's their privacy policy.

If you don't want to do this, you can email us instead at contact@anvil.works.

Using MySQL from an Anvil app

Are you new here?

Anvil is a tool for building full-stack web apps with nothing but Python and a drag-and-drop designer. Learn more on our website, or sign up and try it yourself -- it's free!

It’s easy to access a MySQL database from an Anvil app!

Because an Anvil app has a full Python instance in the back-end, you can use a MySQL driver such as Pymysql to control your MySQL database server, as you would in any Python environment.

Here’s an example of querying a MySQL database from an Anvil server function:

import pymysql

def connect():
  connection = pymysql.connect(host='db.example.com',
                               port=3306,
                               user='root',
                               password=anvil.secrets.get_secret('db_password'),
                               cursorclass=pymysql.cursors.DictCursor)

@anvil.server.callable
def get_people():
  conn = connect()
  with conn.cursor() as cur:
    cur.execute("SELECT name,date_of_birth,score FROM users")
    return cur.fetchall()

And here’s how you’d use it in your Forms to display data with a Data Grid:

class Form1(Form1Template):

  def __init__(self, **properties):
    # Set Form properties and Data Bindings.
    self.init_components(**properties)

    # Any code you write here will run when the form opens.

    self.repeating_panel_1.items = anvil.server.call('get_people')

(Note 1: This example uses the App Secrets service to store your database password encrypted, rather than leaving it “in the clear” in your source code.)

(Note 2: This example uses DictCursor to return SELECT results as lists of dictionaries. This data format is easy to use with Anvil’s Data Grids.)

Do I need MySQL to use Anvil?

No, you don’t!

Anvil also has a built-in database system called Data Tables (here’s a tutorial). Data Tables have visual designer for composing a schema, and Python methods for searching. Data Tables is backed by PostgreSQL, which provides robustness and scalability. On the business plan, Data Tables can be accessed in SQL, but most users prefer to use the Python API.