Skip to content

Sqlalchemy Demo

python
import sqlalchemy as db
from urllib.parse import quote_plus
from sqlalchemy.orm import declarative_base, sessionmaker
from sqlalchemy import Column, Integer, String
import os

DB_DRIVER='mysql'
DB_HOST=''
DB_PORT=3306
DB_DATABASE=''
DB_USERNAME='root'
DB_PASSWORD=''

url = f"{DB_DRIVER}://{DB_USERNAME}:{quote_plus(DB_PASSWORD)}@{DB_HOST}:{DB_PORT}/{DB_DATABASE}"
engine = db.create_engine(url, echo=True)

Base = declarative_base()
class Domain(Base):
    __tablename__ = ''
    id = Column(Integer, primary_key=True)
    url = Column(String(100))
    url_tag = Column(String(20))

text = ""
Session = sessionmaker(bind=engine)
session = Session()
for d in session.query(Domain).order_by(Domain.id):
    text += f"{d.id},{d.url},{d.url_tag}\n"

with open("exported_data.csv","w",encoding="utf-8") as fp:
	fp.write(text)

Released under the MIT License.