SQLALchemy (ORM工具)[PostgreSQL为例]
文章目录
- SQLAlchemy Basics Tutorial
- Install a Postgres server locally and create a database
- Install requirements
- 创建用户与密码设置
- 创建数据库并指定一个拥有者
- 删除数据库
- 查看数据库
- 切换到另一个数据库
- sqlalchemy连接数据库
- Create a table
- 查看表格是否创建成功
- Inserting rows
- Querying rows
- Load CSVs Into PostgreSQL by SQLAlchemy
SQLAlchemy Basics Tutorial
入口 讲了不少基本概念和基本操作,建议首先学习下
Install a Postgres server locally and create a database
Install requirements
- PostgreSQL ubuntu安装教程
- Psycopg2
- SQLAlchemy
安装SQLAlchemy, Psycopg2
conda 安装
conda install -c anaconda psycopg2 -y
conda install -c anaconda sqlalchemy -y
pip 安装
pip install sqlalchemy
pip install psycopg2
Ubuntu 安装 PostgreSQL
sudo apt-get update
sudo apt-get install postgresql postgresql-client
安装完毕后,系统会创建一个数据库超级用户 postgres,密码为空。
sudo -i -u postgres
# 这时使用以下命令进入 postgres,输出以下信息,说明安装成功:
~$ psql
psql (12.4 (Ubuntu 12.4-0ubuntu0.20.04.1))
Type "help" for help.postgres=#
创建用户与密码设置
postgres=# \password postgres # 为postgres用户设置一个密码
postgres=# CREATE USER zdx WITH PASSWORD '123456'; # 创建用户
创建数据库并指定一个拥有者
postgres=# CREATE DATABASE wordcount_dev OWNER zdx;
删除数据库
postgres=# DROP DATABASE wordcount_dev;
查看数据库
postgres=# \lList of databasesName | Owner | Encoding | Collate | Ctype | Access privileges
---------------+----------+----------+-------------+-------------+-----------------------postgres | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |template0 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres +| | | | | postgres=CTc/postgrestemplate1 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres +| | | | | postgres=CTc/postgreswordcount_dev | zdx | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
(4 rows)
切换到另一个数据库
postgres=# \c wordcount_dev
You are now connected to database "wordcount_dev" as user "postgres".
wordcount_dev=#
Using Python with SQLAlchemy to connect to the database and create tables
到这里,数据库已经建好了,所以下面就开始使用python 中的SQLAlchemy库来连接数据库并创建一些表
sqlalchemy连接数据库
import sqlalchemy as db
# Scheme: "postgres+psycopg2://<USERNAME>:<PASSWORD>@<IP_ADDRESS>:<PORT>/<DATABASE_NAME>"
DATABASE_URI = 'postgres+psycopg2://zdx:123456@localhost:5432/wordcount_dev'
engine = db.create_engine(DATABASE_URI)
Create a table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, Date
Base = declarative_base()class Book(Base):__tablename__ = 'books'id = Column(Integer, primary_key=True)title = Column(String)author = Column(String)pages = Column(Integer)published = Column(Date)def __repr__(self):return "<Book(title='{}', author='{}', pages={}, published={})>"\.format(self.title, self.author, self.pages, self.published)Base.metadata.create_all(engine)
查看表格是否创建成功
wordcount_dev=# \d+List of relationsSchema | Name | Type | Owner | Size | Description
--------+--------------+----------+-------+------------+-------------public | books | table | zdx | 8192 bytes |public | books_id_seq | sequence | zdx | 8192 bytes |
(2 rows)
Destroy all table in the database
Base.metadata.drop_all(engine)
Inserting rows
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
s = Session() # Working with sessions
from datetime import datetime
book = Book(title='Deep Learning',author='Ian Goodfellow',pages=775,published=datetime(2016, 11, 18)
)
s.add(book)
s.commit()
查看刚插入的记录
wordcount_dev=# select * from books;id | title | author | pages | published
----+---------------+----------------+-------+------------1 | Deep Learning | Ian Goodfellow | 775 | 2016-11-18
(1 row)
Querying rows
s.query(Book).first()
Out:
<Book(title='Deep Learning', author='Ian Goodfellow', pages=775, published=2016-11-18 00:00:00)>
s.close() # close the current session
Load CSVs Into PostgreSQL by SQLAlchemy
- By pandas
- transaction commands, which means that all commands must be done successfully or all should rollback in case of an error
- 比较完整的一个大例子 (但还是插入单个表,但代码的注释写的很详细,有助于了解更多的细节)
SQLALchemy (ORM工具)[PostgreSQL为例]相关推荐
- Python数据库ORM工具sqlalchemy的学习笔记
SQLAlchemy是python的一个数据库ORM工具,提供了强大的对象模型间的转换,可以满足绝大多数数据库操作的需求,并且支持多种数据库引擎(sqlite,mysql,postgres, mong ...
- java 连接 postgresql_java如何连接数据库并对其操作(以PostgreSQL为例)
nblogs-markdown"> java如何连接数据库并对其操作(以PostgreSQL为例)相关概念 JDBC(Java Data Base Connectivity)是一种用于 ...
- 转载--SqlAlchemy ORM 学习
转载原文地址:http://blog.csdn.net/yueguanghaidao/article/details/7485345,http://blog.csdn.net/yueguanghaid ...
- SQLAlchemy ORM教程之三:Relationship
建立关系 之前我们已经建立了一个用户(User)表,现在我们来考虑增加一个与用户关联的新的表.在我们的系统里面,用户可以存储多个与之相关的email地址.这是一种基本的一对多的关系.我们把这个新增加的 ...
- SQLAlchemy ORM教程之二:Query
Query Session的query函数会返回一个Query对象.query函数可以接受多种参数类型.可以是类,或者是类的instrumented descriptor.下面的这个例子取出了所有的U ...
- sql python 教程_Python SQLAlchemy ORM教程(3)
由于SQLAlchemy 中文资料比较少,所以根据官网给的tutorial外加其他大佬写的中文资料整合以后准备写一个SQLAlchemy 系列的基础入门教程.本系列可能会夹杂一些个人对于python ...
- 介绍一个C++的ORM工具ODB(一) | C瓜哥的博客
介绍一个C++的ORM工具ODB(一) | C瓜哥的博客 介绍一个C++的ORM工具ODB(一) 前段时间了解了下ORM(对象关系映射),然后就找了下C++的ORM框架,发现真的是很少,主要就下面几种 ...
- python SQLAlchemy数据库工具
一.sqlalchemy概述与架构 1.SQLAlchemy SQLAlchemy是Python编程语言下的一款开源软件.提供SQL包以及对象关联映射(ORM)工具,使用MIT许可证 SQLAlche ...
- python 之路,Day11 (下)- sqlalchemy ORM
python 之路,Day11 - sqlalchemy ORM 本节内容 ORM介绍 sqlalchemy安装 sqlalchemy基本使用 多外键关联 多对多关系 表结构设计作业 1. ORM介绍 ...
最新文章
- 设置参数cocos2d-x 2.x 进度条CCProgressTimer
- 荷兰版手工耿手挖8小时沼气,让自制摩托车不花1毛钱飞驰20公里
- python详细安装教程3.8.3-Python下载 v3.8.3 官方中文版
- NSURLRequest详解IOS最基础的api
- 计算机三级标题,计算机三级考试题目
- cannot add new member解决方法
- 微信和简书输入框文本选择手柄小bug
- 评分卡模型开发(二)--用户数据异常值处理
- 刚刚!腾讯宣布扩招8000人,算法岗成最大亮点!
- vscode 修改(自定义)插件的快捷键
- 分享:世界机场代码(ICAO)[带经纬度]
- u盘写保护无法格式化的修复
- leetcode链表总结
- LaTex 常用数学公式符号速记
- Socket 多人聊天室的实现 (含前后端源码讲解)(一)
- Flutter时间轴
- 深夜切题——Doubles
- 2022年1111/双11淘宝/天猫/京东任务自动助手,分享源码学习
- 平移计算机图形学代码注释,求代码注释:计算机图形学的OpenGL画四面体。高手来吧。争取每句都注释下。谢谢...
- 小米6怎样打开位置服务器,小米手环6gps定位功能在哪打开?经常无法定位怎么办...