An example of creating a table using sqlalchemy in python: pythonsqlalchemy

Source: Internet
Author: User

An example of creating a table using sqlalchemy in python: pythonsqlalchemy

How to Create a table instance using sqlalchemy in python

Creating a table through sqlalchemy requires three elements: Engine, base class, and element.

from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column,Integer,String 

Engine: physical database connection

engine = create_engine('mysql+pymysql://godme:godme@localhost/godme',encoding='utf-8',echo=True) 

Input parameters: Database Type + Connection database + User Name + password + host, character encoding, whether to print table creation details

Base class:

Base = declarative_base() 

Element:

class User(Base):   __tablename__ = 'user'   id = Column(Integer,primary_key=True)   name = Column(String(32))   password = Column(String(64)) 

Basic elements:

_ Tablename __: specifies the table name Column: Row declaration. You can specify the length of the primary key Integer: Data Type String: data type.

Create:

Base.metadata.create_all(engine) 

Basic Process:

1. Obtain the physical database connection
2. Create a class that inherits the base class and describe the database structure with the basic type.
3. base class call class structure, create a data table on the engine according to the description

If you have any questions, please leave a message or go to the community on this site for discussion. Thank you for reading this article. Thank you for your support!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.