Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Sqlalchemy is easy to use

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

First, sqlalchemy connects to the database.

Installation:

Pip install sqlalchemy

Sqlalchemy View version:

Import sqlalchemy

Sqlalchemy.__version__

Sqlalchemy connection to the database:

From sqlalchemy import create_engine

HOST='127.0.0.1'

PORT='3306'

DATABASE='test'

USERNAME='test'

PASSWORD='pass'

DB_URL = 'mysql+pymysql:// {}: {} @ {}: {} / {}? charset=utf8'.format (

USERNAME, PASSWORD, HOST, PORT, DATABASE

)

Engin = create_engine (DB_URL, echo=False)

The simple process for sqlalchemy to create a table:

1. Create a base class

From sqlalchemy.ext.declarative import declarative_base

Base = declarative_base ()

two。 Create a class

From sqlalchemy import Column, Integer, String

Class User (Base):

_ _ tablemame__ = 'users' # the name of the data table

Id = Column (Integer, Sequence ('user_id_seq'), Primary_key=True) # set as the primary key

Name = Column (String (20), nullable=False) # non-empty

Password = Column (String (255), nullable=False)

Create a table:

Base.metadata.create_all (engine)

Create an object

Zs_user = User (name='zs', fullname='ZhangSan', password='password')

Zs.name

Zs

Create Session

From sqlalchemy.orm import sessionmaker

Session = sessionmaker (bind=engine)

Add update object

Add a zs_user object to the session

Session.add (zs_user)

Through conditional query

Zs = session.query (User). Filter_by (name='zs'). First ()

You can use the add_all () function to add multiple User objects at one time,

Session.add_all (

User (name='ls', fullname='lisi', password='pass')

User (name='ww', fullname='wangwu', password='pass')

)

View the status waiting for submission:

Session.new

Commit changes to the database:

Session.commit ()

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report