1. 程式人生 > >20180202之engine,URL,base,session

20180202之engine,URL,base,session

-c ext tab postgresq mem 使用 create ldb string

  1. SQLAlchemy版本信息檢查
  2. import sqlalchemy
    print(sqlalchemy.__version__)
  3. 數據庫鏈接
    1. 創建engine
    2. from sqlalchemy import create_engine
      engin=create_engine("dialect+driver://username:password@host:port/database")
    3. 數據庫URL支持
      1. Postgresql:
      2. # default
        engine = create_engine(postgresql://scott:tiger@localhost/mydatabase)
        # psycopg2
        engine = create_engine(
        postgresql+psycopg2://scott:tiger@localhost/mydatabase) # pg8000 engine = create_engine(postgresql+pg8000://scott:tiger@localhost/mydatabase)
      3. MySQL:
      4. # default
        engine = create_engine(mysql://scott:tiger@localhost/foo)
        # mysql-python
        engine = create_engine(mysql+mysqldb://scott:tiger@localhost/foo)
        # MySQL-connector-python
        engine = create_engine(mysql+mysqlconnector://scott:tiger@localhost/foo) # OurSQL engine = create_engine(mysql+oursql://scott:tiger@localhost/foo)
      5. Oracl:
        engine = create_engine(oracle://scott:[email protected]:1521/sidname)
        engine = create_engine(oracle+cx_oracle://scott:tiger@tnsname)
      6. Microsoft SQL Server:
        #
        pyodbc engine = create_engine(mssql+pyodbc://scott:tiger@mydsn) # pymssql engine = create_engine(mssql+pymssql://scott:tiger@hostname:port/dbname)
      7. SQLite:
        #Unix/Mac - 4 initial slashes in total
        engine = create_engine(sqlite:////absolute/path/to/foo.db)
        #Windows
        engine = create_engine(sqlite:///C:\\path\\to\\foo.db)
        #Windows alternative using raw string
        engine = create_engine(rsqlite:///C:\path\to\foo.db)
        #Memony SQLite database
        engine = create_engine(sqlite://)
  4. Declarative方法對象
    1. 基類創建
    2. from sqlalchemy.ext.declarative import declarative_base
      Base = declarative_base()
    3. 基於基類創建映射類
    4. from sqlalchemy import Column,Integer,String
      class User(Base):
          __tablename__="user"
          id=Column(Integer,primary_key=True)
          name=Column(String)
    5. 通過映射類創建實例
      user = User(name=Huangy,fullname=Huangya, password=123.com)
  5. Session,用於ORM與數據庫的鏈接,創建session的時候需綁定數據庫engine
  6. from sqlalchemy.orm import sessionmaker
    Session=sessionmaker(bind=engine)
    1. 需要session時,再初始化
    2. #當需要和數據庫鏈接的時候,再初始化一個session對象
      session=Session()
    3. 雖然以上操作session和engine已經關聯,但是無任何鏈接,當使用的時候,再從engine維護的鏈接池中檢索是否存在鏈接,若存在則保持,直到close或更改。

20180202之engine,URL,base,session