2.1 問題
創建employees表
創建部門表
創建salary表
表間創建恰當的關係
2.2 步驟
實現此案例需要按照如下步驟進行。
步驟一:SQLAlchemy安裝
注意:sqlalchemy可以連接各種數據庫
[root@serwang ~]# pip3 install sqlalchemy
Collecting sqlalchemy
Downloading http://pypi.doubanio.com/packages/aa/cc/48eec885d81f7260b07d
961b3ececfc0aa82f7d4a8f45ff997e0d3f44ba/SQLAlchemy-1.2.11.tar.gz (5.6MB)
...
...
Installing collected packages: sqlalchemy
Running setup.py install for sqlalchemy ... done
Successfully installed sqlalchemy-1.2.11
You are using pip version 9.0.1, however version 18.0 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
步驟二:爲SQLAlchemy創建數據庫
MariaDB [tedu]> CREATE DATABASE tarena DEFAULT CHARSET 'utf8';
步驟三:創建部門表,創建dbconn.py文件,編寫如下代碼:
- 創建連接到數據庫的引擎
[root@localhost day10]# vim dbconn.py
#!/usr/bin/env python3
from sqlalchemy import create_engine
#創建連接到數據庫的引擎
engine = create_engine(
#指定數據庫、用戶名、密碼、連接到哪臺服務器、庫名等信息
'mysql+pymysql://root:tedu.cn@localhost/tarena?charset=utf8',
encoding='utf8',
echo=True #終端輸出
)
2)創建ORM映射,生成ORM映射所需的基類
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
3)自定義映射類,創建部門表
from sqlalchemy import Column, String, Integer
class Departments(Base): # 必須繼承於Base
__tablename__ = 'departments' # 庫中的表名
# 每個屬性都是表中的一個字段,是類屬性
dep_id = Column(Integer, primary_key=True) #Integer整數類型,primary_key主鍵
# String字符串類型,nullable非空約束,unique唯一性約束
dep_name = Column(String(20), nullable=False, unique=True)
def __str__(self):
return '[部門ID:%s, 部門名稱:%s]' % (self.dep_id, self.dep_name)
if __name__ == '__main__':
# 在數據庫中創建表,如果庫中已有同名的表,將不會創建
Base.metadata.create_all(engine)
4)測試腳本執行,生成部門表
[root@localhost day10]# python3 dbconn.py #成功生成部門表
5)進入數據庫查看結果
#登錄數據庫
[root@localhost day10]# mysql -uroot -ptedu.cn
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 5
Server version: 5.5.56-MariaDB MariaDB Server
Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
#查看數據庫表
MariaDB [(none)]> use tarena;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
MariaDB [tarena]> show tables;
+------------------+
| Tables_in_tarena |
+------------------+
| departments |
+------------------+
1 row in set (0.00 sec)
MariaDB [tarena]> show create table departments;
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| departments | CREATE TABLE `departments` (
`dep_id` int(11) NOT NULL AUTO_INCREMENT,
`dep_name` varchar(20) NOT NULL,
PRIMARY KEY (`dep_id`),
UNIQUE KEY `dep_name` (`dep_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+-------------+-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
步驟四:創建員工表,在dbconn.py文件中添加如下數據:
1)創建員工表
from sqlalchemy import ForeignKey 導入外鍵
class Employees(Base): # 必須繼承於Base
__tablename__ = 'employees' # 庫中的表名
# 每個屬性都是表中的一個字段,是類屬性
emp_id = Column(Integer, primary_key=True) #Integer整數類型,primary_key主鍵
name = Column(String(20), nullable=False) # String字符串類型,nullable非空約束
gender = Column(String(6))
phone = Column(String(11))
email = Column(String(50))
dep_id = Column(Integer, ForeignKey('departments.dep_id')) #與departments中dep_id做外鍵關聯
def __str__(self):
return '員工:%s' % self.name
4)測試腳本執行,生成員工表
[root@localhost day10]# python3 dbconn.py #成功生成員工表
5)進入數據庫查看結果
#登錄數據庫
[root@localhost day10]# mysql -uroot -ptedu.cn
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 5
Server version: 5.5.56-MariaDB MariaDB Server
Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
#查看數據庫表
MariaDB [(none)]> use tarena;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
MariaDB [tarena]> show tables;
+------------------+
| Tables_in_tarena |
+------------------+
| departments |
| employees |
+------------------+
2 rows in set (0.00 sec)
步驟五:創建工資表,在dbconn.py文件中添加如下數據:
1)創建工資表
from sqlalchemy import Date 導入外鍵
class Employees(Base): # 必須繼承於Base
__tablename__ = 'employees' # 庫中的表名
# 每個屬性都是表中的一個字段,是類屬性
emp_id = Column(Integer, primary_key=True) #Integer整數類型,primary_key主鍵
name = Column(String(20), nullable=False) # String字符串類型,nullable非空約束
gender = Column(String(6))
phone = Column(String(11))
email = Column(String(50))
dep_id = Column(Integer, ForeignKey('departments.dep_id')) #與departments中dep_id做外鍵關聯
def __str__(self):
return '員工:%s' % self.name
class Salary(Base): # 必須繼承於Base
__tablename__ = 'salary' # 庫中的表名
auto_id = Column(Integer, primary_key=True) #Integer整數類型,primary_key主鍵
date = Column(Date) #導入日期
emp_id = Column(Integer, ForeignKey('employees.emp_id')) #與employees中emp_id做外鍵關聯
basic = Column(Integer) #基本工資
awards = Column(Integer) #獎金
4)測試腳本執行,生成員工表
[root@localhost day10]# python3 dbconn.py #成功生成工資表
5)進入數據庫查看結果
#登錄數據庫
[root@localhost day10]# mysql -uroot -ptedu.cn
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 5
Server version: 5.5.56-MariaDB MariaDB Server
Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
#查看數據庫表
MariaDB [(none)]> use tarena;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
MariaDB [tarena]> show tables;
+------------------+
| Tables_in_tarena |
+------------------+
| departments |
| employees |
| salary |
+------------------+
3 rows in set (0.00 sec)