Sherif Ahmed
Sherif Ahmed

Reputation: 11

How to add table to database?

I am trying to use this code to add a table to a database in a Flask app on localhost - but it does not work. What should I do?

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
    
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']='postgresql://postgres:123@localhost:5432/postgres'

db = SQLAlchemy(app)
class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(), nullable=False)

db.create_all()

Upvotes: 0

Views: 93

Answers (3)

Sherif Ahmed
Sherif Ahmed

Reputation: 11

I changed my app name from "flask-hello-app" to "app" and typed these 3 commands in terminal:

python
from app import db
db.create_all()

and it worked for me.

Upvotes: 1

yimingStar
yimingStar

Reputation: 53

I just try your code using both Postgres and MySQL

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://root:55665566@localhost:5432/test'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

# from yourapplication import db
db.create_all()

Since I have created the table successfully, I suggest you check some details below

  1. Check the role attribute for the account. enter image description here
  2. Check the connection to the database, using command \du to confirm your accounts info, suppose you need to create a user 'postgres' which should show up in the table above.

Upvotes: 0

i3bdulr7man
i3bdulr7man

Reputation: 75

db.session.commit()

Good luck.

Upvotes: 0

Related Questions