How do I connect to a MySQL Database in Python?

后端 未结 25 1505
眼角桃花
眼角桃花 2020-11-21 07:43

How do I connect to a MySQL database using a python program?

25条回答
  •  被撕碎了的回忆
    2020-11-21 08:21

    SqlAlchemy


    SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL. SQLAlchemy provides a full suite of well known enterprise-level persistence patterns, designed for efficient and high-performing database access, adapted into a simple and Pythonic domain language.

    Installation

    pip install sqlalchemy
    

    RAW query

    from sqlalchemy import create_engine
    from sqlalchemy.orm import sessionmaker, scoped_session
    
    engine = create_engine("mysql://:@/")
    session_obj = sessionmaker(bind=engine)
    session = scoped_session(session_obj)
    
    # insert into database
    session.execute("insert into person values(2, 'random_name')")
    session.flush()
    session.commit()
    

    ORM way

    from sqlalchemy import Column, Integer, String
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import create_engine
    from sqlalchemy.orm import sessionmaker, scoped_session
    
    Base = declarative_base()
    engine = create_engine("mysql://:@/")
    session_obj = sessionmaker(bind=engine)
    session = scoped_session(session_obj)
    
    # Bind the engine to the metadata of the Base class so that the
    # declaratives can be accessed through a DBSession instance
    Base.metadata.bind = engine
    
    class Person(Base):
        __tablename__ = 'person'
        # Here we define columns for the table person
        # Notice that each column is also a normal Python instance attribute.
        id = Column(Integer, primary_key=True)
        name = Column(String(250), nullable=False)
    
    # insert into database
    person_obj = Person(id=12, name="name")
    session.add(person_obj)
    session.flush()
    session.commit()
    

提交回复
热议问题