python ORM of sqlalchemy

Cutting-edge
object-relational mapping ORM is commonly used to programming in the practical application of technology, it builds a bridge between object and relational, object-type data reception and relational database data be transformed into each other through this bridge. Simply means that developers in the use of ORM programming model, do not need to write SQL statements to manipulate the database, but the use of a range of functions and methods to complete the operation on the database.

Python ORM framework of the current popular mainly SQLAlchemy framework that is compatible with MySQL, SQLite, Oracle and other relational databases.

Preparations
to install SQLAlchemy framework

pip3 install sqlalchemy
connected database
SqlAlchemy module when connected to a database connected to specify the URI, a parameter for indicating the type of the database account password and the like, in the format:

(1) MySQL database

mysql + frameworkname: // username: password @ address: port / databasename
parameters explained:

frameworkname: module name database using the connection, is used in this section PyMySQL;
username: database user name;
password: Password connection;
address: connection address;
Port: port;
DatabaseName: database name.
(2) SQLite database

# Unix / Mac system

SQLite: ////absolutepath/dbname.db

# Windows system

sqlite: /// C: \\ absolutepath \\ dbname.db
of parameters:

absolutepath: absolute path;
dbname: database file name.
Examples

Connect_orm.py #
from SQLAlchemy Import create_engine

the try:
# connection MySQL database, address: localhost: 3306, account: the root, Password: 123, Database: Test
MySQLEngine create_engine = ( '+ MySQL pymysql: // the root: 123 @ localhost: 3306 / the Test? charset = utf8 ', encoding =' utf8 ')
Print (' MySQL database connection success ', MySQLEngine)
# SQLite database connection, if the current directory does not exist test.db file is automatically generated
SQLiteEngine = create_engine (' SQLite: ///: test.db ', encoding =' UTF-. 8 ')
Print (' SQLite database connection success', SQLiteEngine)
the except Exception aS E:
Print ( 'database connection failure', e)
the result of execution :

MySQL database connection success Engine (mysql + pymysql: // root : *** @ localhost:? 3306 / student charset = utf8)
connected SQLite database successfully Engine (sqlite: ///: test.db)
add, delete, change, check
1. create a database table
to be created STUDENT table:

Column Name

Types of

Remark

SNO

CHAR(10)

NOT NULL

SNAME

CHAR(20)

Primary key

program: 

Create_table_orm.py #
from SQLAlchemy Import Column, String, create_engine
from sqlalchemy.orm Import sessionmaker
from sqlalchemy.ext.declarative Import declarative_base

# create a base class
BASE = declarative_base ()

# define student objects
class Student (BASE):
# table name: the STUDENT
__tablename__ = 'the STUDENT'
# student number
SnO = the Column (String (10))
# name
sname = the Column (String (20 is), primary_key = True)
# Create a table of parameters
__table_args__ = {
"mysql_charset": "UTF8"
}

the try :
# connect to the MySQL database, address: localhost: 3306, account: root, password: 123, database: the Test
MySQLEngine = create_engine ( '+ MySQL pymysql: // root: 123 @ localhost: 3306 / charset = utf8 the Test?', encoding = 'utf-8')
# Create STUDENT table
BASE.metadata.create_all (MySQLEngine)
Print ( 'STUDENT table created successfully')
the except Exception AS E:
Print ( "SQLite database connection failure", E)
2. Insert data
# insertData_orm.py
from the Column SQLAlchemy Import, String, create_engine
from sqlalchemy.orm Import sessionmaker
from sqlalchemy.ext.declarative Import declarative_base

# create a base class
bASE = declarative_base ()

# define student objects
class student (bASE):
name # table: sTUDENT
__tablename__ = 'sTUDENT'
# student ID
Column = SnO (String (10))
# name
sname = Column (String (20), primary_key = True)
# create a parameter table
__table_args__ = {
"mysql_charset": "utf8"
}

try:
# Connect to the MySQL database
MySQLEngine = create_engine ( '+ MySQL pymysql: // root: 123 @ localhost: 3306 / charset = utf8 the Test?', Encoding = 'utf8')
# Create a MySQL type
MySQLSession = sessionmaker (bind = MySQLEngine)
Create the session object #
session MySQLSession = ()

# insert data using ORM
# Create Student object
Stu = Student (sname = 'John Doe', SnO = '2,016,081,111')
# created object added to the session
session.add (Stu)

# using native SQL insert data
session.execute (
"iNSERT iNTO sTUDENT VALUES ( '2,016,081,115', 'Wu Fang'), ( '2016081116', 'Hu Yue')")
# submitted to the database
Session.commit ()
# close the session
Session.close ()
Print ( 'data is successfully inserted')
the except Exception AS E:
Print ( "SQLite database connection failure ", E)
3. query data
SelectData_orm.py #
from SQLAlchemy Import Column, String, create_engine
from sqlalchemy.orm Import sessionmaker
from sqlalchemy.ext.declarative Import declarative_base

# create a base class
BASE = declarative_base ()

# define student objects
class Student (BASE):
# table name:
__tablename__ = 'the STUDENT'

sname = the Column (String (20 is), primary_key = True)
SnO = the Column (String (10))

DEF __str __ (Self): # format of the output data which inquires
return '% s,% s' % ( self.sname, self.sno)

the try:
# connect to the MySQL database
MySQLEngine = create_engine ( '+ MySQL pymysql: // root: 123 @ localhost: 3306 / charset = utf8 the Test?', encoding = 'utf8')
# create MySQL type
MySQLSession = sessionmaker (the bind = MySQLEngine)
# create a session object
= MySQLSession the session ()
# inquiry number 2016081111 school students
Stu = session.query (Student) .filter (Student.sno == '2016081111')
# query all data
Stus = session.query (Student) .all ()
Print ( 'type of query results:', type (Stu))
Print ( "All the STUDENT table: ')
for Row in Stus:
Print (Row)
# close the session
Session.close ()
the except Exception AS E:
Print (" SQLite database connection failure ", e)
the program execution results:

The type of query results: <class 'sqlalchemy.orm.query.Query'>
All STUDENT table:
Wu Fang, 2016081115
Joe Smith, 2016081111
Hu Yue, 2016081116
4. Modify the data
# selectData_orm.py
from SQLAlchemy Import Column, String, create_engine
from sqlalchemy.orm Import sessionmaker
from sqlalchemy.ext.declarative Import declarative_base

# create a base class
bASE = declarative_base ()

# define student objects
class student (bASE):
# table name:
__tablename__ = 'sTUDENT'

sname = Column (String ( 20 is), primary_key = True)
SnO the Column = (String (10))

DEF __str __ (Self): # query the format of the output data
return '% S, S%'% (self.sname, self.sno)

the try:
# MySQL database connection
= Create_engine MySQLEngine ( '+ MySQL pymysql: // root: 123 @ localhost:? 3306 / charset = utf8 the Test', encoding = 'utf8')
# Create a MySQL type
MySQLSession = sessionmaker (the bind = MySQLEngine)
# Create a session object
= MySQLSession the session ()
# inquiry number 2016081111 school students
. Stu = session.query (student) .filter (Student.sno == '2016081111') First ()
Print ( 'before change:', Stu)
# name change Hua is
Stu.sname = 'Hua'
committed to the database #
Session.commit ()
( 'post-change:', Stu) Print
# close the session
Session.close ()
the except Exception aS E:
Print ( "connection failed database SQLite ", e)
the program execution results:

Before changing: Joe Smith, 2016081111
After: Li Hua, 2016081111
5. Delete data
# deleteData_orm.py
from SQLAlchemy Import Column, String, create_engine
from sqlalchemy.orm Import sessionmaker
from sqlalchemy.ext.declarative Import declarative_base

# create a base class
BASE = declarative_base ()

# define student Object
class student (BASE):
# table name:
__tablename__ = 'sTUDENT'

sname = Column (String (20), primary_key = True)
SnO = Column (String (10))

DEF __str __ (Self) : # query the format of the output data
return '% S, S%'% (self.sname, self.sno)

the try:
# MySQL database connection
MySQLEngine = create_engine ( 'mysql + pymysql : // root: 123 @ localhost: 3306 / the Test? charset = utf8 ', encoding =' utf8 ')
# create a MySQL type
= Sessionmaker MySQLSession (the bind = MySQLEngine)
# Create a session object
session = MySQLSession ()
# Query student number 2016081111 for students of
the before = session.query (Student) .filter (Student.sno == '2016081111'). First ()
Print ( 'before deletion:', the before)
# delete the data
. session.query (Student) .filter (Student.sno == '2016081111') the delete ()
# submitted to the database
Session.commit ()
the After = session.query (Student .) .filter (Student.sno == '2,016,081,111') First ()
Print ( 'delete:', after)
# close the session
Session.close ()
the except Exception AS E:
Print ( "SQLite database connection failure", e )
program execution results:

Before deleting: Li Hua, 2016081111
after deleting: None
 

Guess you like

Origin www.cnblogs.com/aibabel/p/11489566.html