2

I am trying to create a database with the module databases

This is the code that I have tried

from databases import Database
database = Database('sqlite:///example.db')
await database.connect()

query = """CREATE TABLE HighScores (id INTEGER PRIMARY KEY, name VARCHAR(100), score INTEGER)"""
await database.execute(query=query)

query = "INSERT INTO HighScores(name, score) VALUES (:name, :score)"
values = [
    {"name": "Daisy", "score": 92},
    {"name": "Neil", "score": 87},
    {"name": "Carol", "score": 43},
]
await database.execute_many(query=query, values=values)

query = "SELECT * FROM HighScores"
rows = await database.fetch_all(query=query)
print('High Scores:', rows)

Its returns an error of "SyntaxError: 'await' outside function"

How do I fix this

Cody Brynlund
  • 81
  • 1
  • 8

1 Answers1

2

You cannot use await outside an async function.

async myFunc():
    await database.connect()

however, in order to call the await functions, you need to await them. You can do this by making use of the asyncio package. (So import asyncio ;)

import asyncio
loop = asyncio.run(myFunc()) # this will run a coroutine without awaiting.

You can convert this to work for all of the other functions. However, I would suggest putting everything in myFunc instead of making a new function for everything.

See the docs

12944qwerty
  • 2,001
  • 1
  • 10
  • 30