久久国产成人av_抖音国产毛片_a片网站免费观看_A片无码播放手机在线观看,色五月在线观看,亚洲精品m在线观看,女人自慰的免费网址,悠悠在线观看精品视频,一级日本片免费的,亚洲精品久,国产精品成人久久久久久久

分享

Python3 連接各類數(shù)據(jù)庫

 乙甲壬 2020-07-11

SQLite是一種嵌入式數(shù)據(jù)庫,,SQLite本身是C寫的體積很小,它的數(shù)據(jù)庫就是一個文件,,所以經(jīng)常被集成到各種應(yīng)用程序中,,甚至在iOS和Android的App中都可以集成,。Python內(nèi)置了sqlite3。

復(fù)制代碼
#coding:utf-8import sqlite3conn = sqlite3.connect('test.db')cursor = conn.cursor()# sqlite創(chuàng)建表時,,若id為INTEGER類型且為主鍵,,可以自動遞增,在插入數(shù)據(jù)時id填NULL即可# cursor.execute('create table user(id integer primary key, name varchar(25))') #執(zhí)行一次# 插入一條數(shù)據(jù)cursor.execute('insert into user(id,name)values(NULL,'yjc')')# 返回影響的行數(shù)print(cursor.rowcount)#提交事務(wù),,否則上述SQL不會提交執(zhí)行conn.commit()# 執(zhí)行查詢cursor.execute('select * from user')# 獲取查詢結(jié)果print(cursor.fetchall())# 關(guān)閉游標(biāo)和連接cursor.close()conn.close()
復(fù)制代碼

輸出:

1[(1, 'yjc'), (2, 'yjc')]

我們發(fā)現(xiàn)Python里封裝的數(shù)據(jù)庫操作很簡單:
1,、獲取連接conn;
2,、獲取游標(biāo)cursor,;
3、使用cursor.execute()執(zhí)行SQL語句,;
4,、使用cursor.rowcount返回執(zhí)行insert,update,,delete語句受影響的行數(shù),;
5、使用cursor.fetchall()獲取查詢的結(jié)果集,。結(jié)果集是一個list,,每個元素都是一個tuple,對應(yīng)一行記錄,;
6,、關(guān)閉游標(biāo)和連接。

如果SQL語句帶有參數(shù),,那么需要把參數(shù)按照位置傳遞給cursor.execute()方法,,有幾個?占位符就必須對應(yīng)幾個參數(shù),示例:

cursor.execute('select * from user where name=? ', ['abc'])
為了能在出錯的情況下也關(guān)閉掉Connection對象和Cursor對象,,建議實際項目里使用try:...except:...finally:...結(jié)構(gòu),。

二、Mysql
1. 安裝 PyMysql 庫
pip3 install pymysql
2. 連接數(shù)據(jù)庫的幾種方法
connect()方法用于連接數(shù)據(jù)庫
第一種:將各類字段寫上

db = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='Geek_Web', charset='utf8mb4')
第二種:省略字段

db = pymysql.connect(root,root, Geek_Web)
第三種:構(gòu)建配置文件

config = {

'host':'localhost',
'port':3306,
'user':'root',
'passwd':'root',
'db':'Geek_Web',
'charset':'utf8mb4',
}

db = pymysql.connect(**config)
3. 操作數(shù)據(jù)庫
cursor = db.cursor() # cursor() 方法獲取操作游標(biāo)
sql = 'SELECT * FROM main'
cursor.execute(sql) # 執(zhí)行SQL語句
results = cursor.fetchall() # 獲取所有記錄列表
results = cursor.fetchone() # 獲取一條記錄列表
db.commit() # 沒有設(shè)置默認自動提交,,需要主動提交,,以保存所執(zhí)行的語句
# 除了查詢其他操作都需要保存執(zhí)行
cursor.close()
db.close() # 關(guān)閉數(shù)據(jù)庫連接
4. PyMysql 返回字典數(shù)據(jù)
PyMysql 默認返回是元組,有時候需要返回數(shù)據(jù)庫的字段,,需要把 Key 也返回及返回字典類型

# 在連接數(shù)據(jù)庫時候加上 cursorclass 就可以數(shù)據(jù)庫內(nèi)容以字典格式返回
cursorclass=pymysql.cursors.DictCursor
5. 源碼實例

復(fù)制代碼
#!/usr/bin/env python3# -*- coding: UTF-8 -*-# 安裝PyMySQL# sudo pip install PyMySQLimport pymysqlconfig = {'host':'localhost','port':3306,'user':'root','passwd':'root','db':'Geek_Web','charset':'utf8mb4',# 數(shù)據(jù)庫內(nèi)容以字典格式輸出#'cursorclass':pymysql.cursors.DictCursor,}# 連接數(shù)據(jù)庫def Mysql():# 連接數(shù)據(jù)庫#db = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='Geek_Web', charset='utf8mb4')db = pymysql.connect(**config)#cursor()方法獲取操作游標(biāo) cursor = db.cursor()try:return (db, cursor)except:print('數(shù)據(jù)庫訪問失敗')#def Insert(db, cursor):sql = 'insert into main(id, Tag, Name, Version, Introduce, Class, Worked_OS, Course_URL, Download_URL, Image_URL, Remarks_1, Remarks_2) \values (NULL, '軟件編號', '軟件名稱', '軟件版本', '軟件簡介', '軟件類別', '運行環(huán)境', '教程地址', '下載地址', '圖標(biāo)地址', '備注1', '備注2')'# 執(zhí)行SQL語句cursor.execute(sql)# 沒有設(shè)置默認自動提交,,需要主動提交,以保存所執(zhí)行的語句db.commit()#def Delect(db, cursor):sql = 'DELETE FROM main WHERE Name = '修改后的名字''cursor.execute(sql)db.commit()#def Select(db, cursor):sql = 'SELECT * FROM main'cursor.execute(sql)# 獲取所有記錄列表results = cursor.fetchall()return results#def Update(db, cursor):sql = 'UPDATE main SET Name = '修改后的名字' WHERE Remarks_2 = '備注2''cursor.execute(sql)db.commit()# 關(guān)閉數(shù)據(jù)庫連接def Close(db, cursor):cursor.close()db.close()(db, cursor) = Mysql()print('\n-------------數(shù)據(jù)庫初始狀態(tài)-------------')print(Select(db, cursor))Insert(db, cursor)print('\n-------------數(shù)據(jù)庫插入數(shù)據(jù)-------------')print(Select(db, cursor))Update(db, cursor)print('\n-------------數(shù)據(jù)庫修改數(shù)據(jù)-------------')print(Select(db, cursor))Delect(db, cursor)print('\n-------------數(shù)據(jù)庫刪除數(shù)據(jù)-------------')print(Select(db, cursor))Close(db, cursor)
復(fù)制代碼

6. pymysql使用:

from pymsql import *                                        導(dǎo)入模塊
(db = pymysql.connect(...))                               1,、建立數(shù)據(jù)庫連接
c = db.cursor())                                                 2,、創(chuàng)建游標(biāo)對象
c.execute('insert ....')                                        3、游標(biāo)方法: 
db.commit()                                                       4、提交到數(shù)據(jù)庫
c.close()                                                            5,、關(guān)閉游標(biāo)對象
db.close()                                                          6,、斷開數(shù)據(jù)庫連接 :
connect對象:
db = pymysql.connect(參數(shù)列表)
      1、host :主機地址,本地 localhost
      2,、port :端口號,默認3306
      3,、user :用戶名
      4、password :密碼
      5,、database :庫
      6,、charset :編碼方式,推薦使用 utf8
連接對象的方法:
數(shù)據(jù)庫連接對象(db)的方法
      1、db.close() 關(guān)閉連接
      2,、db.commit() 提交到數(shù)據(jù)庫執(zhí)行
      3,、db.rollback() 回滾
      4、cur = db.cursor() 返回游標(biāo)對象,用于執(zhí)行具體SQL命令
游標(biāo)對象的方法:
游標(biāo)對象(cur)的方法
      1,、cur.execute(sql命令,[列表]) 執(zhí)行SQL命令
      2,、cur.close() 關(guān)閉游標(biāo)對象
      3、cur.fetchone() 獲取查詢結(jié)果集的第一條數(shù)據(jù)
      4,、cur.fetchmany(n) 獲取n條
      5,、cur.fetchall() 獲取所有記錄

三、Mssql
1. 安裝 PyMssql 庫
pip3 install pymysql
2. 連接數(shù)據(jù)庫的方法
Mssql 用字典配置不可以用,,connect() 用來連接數(shù)據(jù)庫

db = pymssql.connect(host='192.0.0.200',user='ymyg',password='ymyg',database='Geek_Web')
3. 操作數(shù)據(jù)庫
和 Mysql 操作方法一模一樣,,只不過將 PyMysql 改為 PyMssql 即可,,參考上面 PyMssql

4. PyMssql 返回字典數(shù)據(jù)
只需要在連接數(shù)據(jù)庫時候加上一個 as_dict 字段,,將值改為 True 即可

db = pymssql.connect(host='192.0.0.200',user='ymyg',password='ymyg',database='Geek_Web',as_dict=True)

5.連接示例

復(fù)制代碼
import timeimport pymssql#import decimalclass MSSQL:  def __init__(self,host,user,pwd,db):    self.host=host    self.user=user    self.pwd=pwd    self.db=db  def GetConnect(self):    if not self.db:      raise(NameError,'沒有目標(biāo)數(shù)據(jù)庫')    self.connect=pymssql.connect(host=self.host,user=self.user,password=self.pwd,database=self.db,charset='utf8')    cur=self.connect.cursor()    if not cur:      raise(NameError,'數(shù)據(jù)庫訪問失敗')    else:      return cur  def ExecSql(self,sql):     cur=self.GetConnect()     cur.execute(sql)     self.connect.commit()     self.connect.close()  def ExecQuery(self,sql):    cur=self.GetConnect()    cur.execute(sql)    resList = cur.fetchall()    self.connect.close()    return resList  def main():  ms = MSSQL(host='192.168.0.108', user='sa', pwd='sa', db='ComPrject')  resList = ms.ExecQuery('select *from TestModel')  print(resList)if __name__ == '__main__':  main()  input('執(zhí)行完成:')
復(fù)制代碼

5. PyMssql 參數(shù)

connect() 參數(shù)

  • dsn 連接字符串 主要用于與之前版本的pymssql兼容
  • user 用戶名
  • password 密碼
  • trusted 布爾值 指定是否使用windows身份認證登陸
  • host 主機名
  • database 數(shù)據(jù)庫
  • timeout 查詢超時
  • login_timeout 登陸超時
  • charset 數(shù)據(jù)庫的字符集
  • as_dict 布爾值 指定返回值是字典還是元組
  • max_conn 最大連接數(shù)

操作方法

  • close() 關(guān)閉游標(biāo)
  • execute(operation) 執(zhí)行操作
  • execute(operation params) 執(zhí)行操作 可以提供參數(shù)進行相應(yīng)操作
  • executemany(operation paramsseq) 執(zhí)行操作 Paramsseq 為元組
  • fetchone() 在結(jié)果中讀取下一行
  • fetchmany(size=None) 在結(jié)果中讀取指定數(shù)目的行
  • fetchall() 讀取所有行
  • nextset() 游標(biāo)跳轉(zhuǎn)到下一個數(shù)據(jù)集

其他方法

  • autocommit(status) 布爾值 指示是否自動提交事務(wù) 默認的狀態(tài)是關(guān)閉的 如果打開 你必須調(diào)用commit()方法來提交事務(wù)
  • close() 關(guān)閉連接
  • cursor() 返回游標(biāo)對象 用于查詢和返回數(shù)據(jù)
  • commit() 提交事務(wù)
  • rollback() 回滾事務(wù)
  • pymssqlCursor類 用于從數(shù)據(jù)庫查詢和返回數(shù)據(jù)
  • rowcount 返回最后操作影響的行數(shù)
  • connection 返回創(chuàng)建游標(biāo)的連接對象
  • lastrowid 返回插入的最后一行
  • rownumber 返回當(dāng)前數(shù)據(jù)集中的游標(biāo)(通過索引)


6. PyMssql 配置文件
在目錄下找到 freetds.conf 

四、Oracle

連接Oracle比MySQL麻煩一些,,連接Oracle需要安裝cx_Oracle和oracle客戶端

1. 安裝 cx_Oracle 庫
pip3 install cx_Oracle

2.

Oracle instant client 下載安裝
1,、下載
下載地址(官網(wǎng)下載需要登錄Oracle賬戶,注冊過程比較簡單):http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html
2,、解壓安裝
解壓下載的壓縮包,,并將對應(yīng)的解壓位置加入系統(tǒng)變量Path中(計算機->屬性->高級系統(tǒng)設(shè)置->環(huán)境變量->系統(tǒng)變量->編輯系統(tǒng)變量->將解壓后的路徑加在后面)
關(guān)于系統(tǒng)變量的配置詳細可參考:http://jingyan.baidu.com/article/3ea51489e1c2b752e61bbad0.html
將Oracle instant client目錄下的oraocci12.dll、oraociei12.dll,、oci.dll復(fù)制到python安裝目

3. 連接數(shù)據(jù)庫的幾種方法
第一種:Oracle 連接方法

db = cx_Oracle.connect('root/root@localhost: 1523/orcl')
第二種:省略字段連接方法

db = cx_Oracle.connect('root', 'root', 'localhost: 1523/orcl')
第三種:dsn 方法

makedsn(IP/HOST, PORT, TNSNAME)
dsn = cx_Oracle.makedsn('localhost','1523','orcl')
db = cx_Oracle.connect('root','root',dsn)
4. 操作數(shù)據(jù)庫
和 Mysql 操作方法一模一樣,,只不過將 PyMysql 改為 cx_Oracle 即可

5. PyMssql 返回字典數(shù)據(jù)
Oracle 返回字典類型比較麻煩,因為 cx_Oracle 沒有集成,,所以需要我們自己寫返回字典的方法

cx_Oracle 的 Cursor 對象有一個屬性 rowfactory 是是用來自定義查詢結(jié)果的預(yù)處理方法的,,定義一個閉包

def makedict(cursor):
cols = [d[0] for d in cursor.description]
def createrow(*args):
return dict(zip(cols, args))
return createrow
并將其注冊給游標(biāo)對象的rowfactory屬性 cursor.rowfactory = makedict(cursor) 得到的結(jié)果自動由元組轉(zhuǎn)為字典了,但要注意,,注冊的動作需要在每次執(zhí)行 cursor.execute 之后都重復(fù)一次,。最終的方法是定義了一個類來繼承 Cursor 對象,這樣就不需要重復(fù)注冊了

6.連接示例

復(fù)制代碼
import cx_Oracle#連接數(shù)據(jù)庫,下面括號里內(nèi)容根據(jù)自己實際情況填寫conn = cx_Oracle.connect('用戶名/密碼@IP:端口號/SERVICE_NAME')# 使用cursor()方法獲取操作游標(biāo)cursor = conn.cursor()#使用execute方法執(zhí)行SQL語句result=cursor.execute('Select member_id from member')#使用fetchone()方法獲取一條數(shù)據(jù)#data=cursor.fetchone() #獲取所有數(shù)據(jù)all_data=cursor.fetchall() #獲取部分數(shù)據(jù),,8條#many_data=cursor.fetchmany(8)print (all_data)db.close()
復(fù)制代碼
復(fù)制代碼
# -*- coding: UTF-8 -*-import cx_Oracle as oracleimport sysimport osimport iosys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'class ExportOracle:    def __init__(self,odbc,user):        self.odbc = odbc        self.user = user     def start(self):        db = oracle.connect(self.odbc)        cursor = db.cursor()        cursor.execute('SELECT NAME,AGE FROM USERS ')        datas = cursor.fetchall()        print(datas) if __name__ == '__main__':    orcleDb_config = {        'odbc':'TEST_XIAOYI/[email protected]:1521/orcl',        'user': 'TEST_XIAOYI',    }    mtables = ExportOracle(orcleDb_config['odbc'],orcleDb_config['user']);    mtables.start();
復(fù)制代碼

五,、ORM

ORM將數(shù)據(jù)庫中的表與面向?qū)ο笳Z言中的類建立了一種映射關(guān)系,ORM可以說是參照映射來處理數(shù)據(jù)的模型,,比如說:需要創(chuàng)建一個表,,可以定義一個類,而這個類存在與表相映射的屬性,,那么可以通過操作這個類來創(chuàng)建一個表,,寫原生 SQL 的過程非常繁瑣,代碼重復(fù),,有了 ORM 你不再需要寫 SQL 語句,。ORM兼容多種數(shù)據(jù)庫系統(tǒng),如sqlite, mysql,、postgresql,。

Peewee
Peewee是一個簡單小巧的Python ORM

SQLAlchemy
既支持原生 SQL,又支持 ORM 的工具,;如果想找一種既支持原生 SQL,,又支持 ORM 的工具,那么 SQLAlchemy 是最好的選擇,。推薦使用SQLAlchemy,。

六、Peewee

Peewee中Model類,、fieldsmodel實例與數(shù)據(jù)庫的映射關(guān)系如下:

也就是說,,一個Model類代表一個數(shù)據(jù)庫的表,一個Field字段代表數(shù)據(jù)庫中的一個字段,,而一個model類實例化對象則代表數(shù)據(jù)庫中的一行,。

定義Model,建立數(shù)據(jù)庫

在使用的時候,,根據(jù)需求先定義好Model,,然后可以通過create_tables()創(chuàng)建表,若是已經(jīng)創(chuàng)建好數(shù)據(jù)庫表了,,可以通過python -m pwiz腳本工具直接創(chuàng)建Model,。

第一種方式:

先定義Model,然后通過db.create_tables()創(chuàng)建或Model.create_table()創(chuàng)建表,。
例如,,我們需要建一個Person表,里面有name,、birthday和is_relative三個字段,,我們定義的Model如下:

from peewee import *# 連接數(shù)據(jù)庫database = MySQLDatabase('test', user='root', host='localhost', port=3306)# 定義Personclass Person(Model): name = CharField() birthday = DateField() is_relative = BooleanField() class Meta: database = database

然后,,我們就可以創(chuàng)建表了

# 創(chuàng)建表Person.create_table()# 創(chuàng)建表也可以這樣, 可以創(chuàng)建多個# database.create_tables([Person])

其中,CharField,、DateField,、BooleanField等這些類型與數(shù)據(jù)庫中的數(shù)據(jù)類型一一對應(yīng),我們直接使用它就行,,至于CharField => varchar(255)這種轉(zhuǎn)換Peewee已經(jīng)為我們做好了 ,。

第二種方式:

已經(jīng)存在過數(shù)據(jù)庫,則直接通過python -m pwiz批量創(chuàng)建Model,。
例如,,上面我已經(jīng)創(chuàng)建好了test庫,并且創(chuàng)建了Person表,,表中擁有id,、name、birthday和is_relative字段,。那么,,我可以使用下面命令:

# 指定mysql,用戶為root,,host為localhost,,數(shù)據(jù)庫為testpython -m pwiz -e mysql -u root -H localhost --password test > testModel.py

然后,輸入密碼,,pwiz腳本會自動創(chuàng)建Model,,內(nèi)容如下:

from peewee import *database = MySQLDatabase('test', **{'charset': 'utf8', 'use_unicode': True, 'host': 'localhost', 'user': 'root', 'password': ''})class UnknownField(object):    def __init__(self, *_, **__): passclass BaseModel(Model):    class Meta:        database = databaseclass Person(BaseModel):    birthday = DateField()    is_relative = IntegerField()    name = CharField()    class Meta:        table_name = 'person'

操作數(shù)據(jù)庫

操作數(shù)據(jù)庫,就是增,、刪,、改和查。

1,、增

直接創(chuàng)建示例,,然后使用save()就添加了一條新數(shù)據(jù)

# 添加一條數(shù)據(jù)p = Person(name='liuchungui', birthday=date(1990, 12, 20), is_relative=True)p.save()
2,、刪

使用delete().where().execute()進行刪除,,where()是條件,execute()負責(zé)執(zhí)行語句,。若是已經(jīng)查詢出來的實例,,則直接使用delete_instance()刪除。

# 刪除姓名為perter的數(shù)據(jù)Person.delete().where(Person.name == 'perter').execute()# 已經(jīng)實例化的數(shù)據(jù), 使用delete_instancep = Person(name='liuchungui', birthday=date(1990, 12, 20), is_relative=False)p.id = 1p.save()p.delete_instance()
3,、改

若是,,已經(jīng)添加過數(shù)據(jù)的的實例或查詢到的數(shù)據(jù)實例,且表擁有primary key時,,此時使用save()就是修改數(shù)據(jù),;若是未擁有實例,,則使用update().where()進行更新數(shù)據(jù)。

# 已經(jīng)實例化的數(shù)據(jù),指定了id這個primary key,則此時保存就是更新數(shù)據(jù)p = Person(name='liuchungui', birthday=date(1990, 12, 20), is_relative=False)p.id = 1p.save()# 更新birthday數(shù)據(jù)q = Person.update({Person.birthday: date(1983, 12, 21)}).where(Person.name == 'liuchungui')q.execute()
4,、查

單條數(shù)據(jù)使用Person.get()就行了,,也可以使用Person.select().where().get()。

若是查詢多條數(shù)據(jù),,則使用Person.select().where(),,去掉get()就行了。語法很直觀,,select()就是查詢,,where是條件,get是獲取第一條數(shù)據(jù),。

# 查詢單條數(shù)據(jù)p = Person.get(Person.name == 'liuchungui')print(p.name, p.birthday, p.is_relative)# 使用where().get()查詢p = Person.select().where(Person.name == 'liuchungui').get()print(p.name, p.birthday, p.is_relative)# 查詢多條數(shù)據(jù)persons = Person.select().where(Person.is_relative == True)for p in persons:    print(p.name, p.birthday, p.is_relative)

七,、SQLAlchemy

使用 sqlalchemy 有3種方式:
方式1, 使用raw sql;
方式2, 使用SqlAlchemy的sql expression;
方式3, 使用ORM.
前兩種方式可以統(tǒng)稱為 core 方式. 對于絕大多數(shù)應(yīng)用, 推薦使用raw sql

通過 engine = create_engine('dialect+driver://username:password@host:port/database')初始化連接
參數(shù)說明:

  • dialect,是數(shù)據(jù)庫類型包括:sqlite, mysql, postgresql, oracle,  mssql等
  • driver,,指定連接數(shù)據(jù)庫的API,,如:`psycopg2``, ``pyodbc``, ``cx_oracle``等,為可選關(guān)鍵字,。
  • username,,用戶名
  • password,密碼
  • host,,網(wǎng)絡(luò)地址,,可以用ip,域名,,計算機名,,當(dāng)然是你能訪問到的。
  • port,,數(shù)據(jù)庫端口,。
  • database,數(shù)據(jù)庫名稱,。

例如
建立mysql的連接方式為:engine = create_engine('mysql://scott:tiger@hostname/dbname',encoding='utf-8', echo=True)
(echo=True,,會顯示在加載數(shù)據(jù)庫所執(zhí)行的SQL語句,可不選此參數(shù),,默認為False)
建立oracle的連接方式為:engine = create_engine('oracle://scott:tiger@hostname/dbname',encoding='utf-8', echo=True)

常用的數(shù)據(jù)庫連接字符串
#sqlite
sqlite_db = create_engine('sqlite:////absolute/path/database.db3')
sqlite_db = create_engine('sqlite://')  # in-memory database
sqlite_db = create_engine('sqlite:///:memory:') # in-memory database

# postgresql
pg_db = create_engine('postgres://scott:tiger@localhost/mydatabase')

# mysql
mysql_db = create_engine('mysql://scott:tiger@localhost/mydatabase')

# oracle
oracle_db = create_engine('oracle://scott:[email protected]:1521/sidname')

一些非主流數(shù)據(jù)庫缺少DB API接口,,比如teradata, 沒有專門的DB API實現(xiàn), 但 odbc driver肯定會提供的. pypyodbc + ODBC driver 應(yīng)該是一個選項. 

sqlalchemy訪問數(shù)據(jù)庫的示例

復(fù)制代碼
from sqlalchemy import Column, String, create_enginefrom sqlalchemy.orm import sessionmakerfrom sqlalchemy.ext.declarative import declarative_base Base = declarative_base() class User(Base): # 表的名字 __tablename__ = 'user' # 表的結(jié)構(gòu) id = Column(String(20), primary_key=True) name = Column(String(20)) # 初始化數(shù)據(jù)庫連接engine = create_engine('mysql+mysqlconnector://root:111111@localhost:3306/test')# 創(chuàng)建DBSession類型DBSession = sessionmaker(bind=engine)# create_engine用來初始化數(shù)據(jù)庫連接.# SQLAlchemy用一個字符串表示連接信息'數(shù)據(jù)庫類型+數(shù)據(jù)庫驅(qū)動名稱://用戶名:口令@機器地址:端口號/數(shù)據(jù)庫名' # # 創(chuàng)建session對象:# session = DBSession()# # 創(chuàng)建新User對象# new_user = User(id='5', name='Bob')# # 添加到session# session.add(new_user)# # 提交保存到數(shù)據(jù)庫# session.commit()# # 關(guān)閉session# session.close() # 可見將關(guān)鍵是獲取session, 然后把對象添加到session, 最后提交并關(guān)閉.(DBSession對象, 可以看做是當(dāng)前數(shù)據(jù)庫的連接) # 查詢session = DBSession()# 創(chuàng)建Query查詢, filter是where條件, 最后調(diào)用one()返回唯一行, 如果調(diào)用all()則返回所有行.user = session.query(User).filter(User.id=='5').one()print('type:', type(user))print('name:', user.name)session.close() # ORM就是把數(shù)據(jù)庫表的行與相應(yīng)的對象簡歷關(guān)聯(lián), 互相轉(zhuǎn)換.# 由于關(guān)系數(shù)據(jù)庫的多個表還可以用外鍵實現(xiàn)一對多, 多對多的關(guān)聯(lián), 相應(yīng)地, ORM框架也可以提供兩個對象之間的一對多, 多對多功能.
復(fù)制代碼
復(fù)制代碼
1、連接數(shù)據(jù)庫在sqlalchemy中,,session用于創(chuàng)建程序與數(shù)據(jù)庫之間的會話,。所有對象的載入和保存都需要通過session對象。from sqlalchemy import create_enginefrom sqlalchemy.orm import sessionmaker# 鏈接數(shù)據(jù)庫采用pymysq模塊做映射,,后面參數(shù)是最大連接數(shù)5ENGINE=create_engine('mysql+pymysql://[email protected]:3306/digchouti?charset=utf8', max_overflow=5)Session = sessionmaker(bind=engine)session = Session()2,、創(chuàng)建映射(創(chuàng)建表)一個映射對應(yīng)著一個Python類,,用來表示一個表的結(jié)構(gòu)。下面創(chuàng)建一個person表,,包括id和name兩個字段,。也就是說創(chuàng)建表就是用python的的類來實現(xiàn)import sqlalchemyfrom sqlalchemy import create_enginefrom sqlalchemy.ext.declarative import declarative_basefrom sqlalchemy import Column, Integer, Stringfrom sqlalchemy.orm import sessionmakerENGINE=create_engine('mysql+pymysql://[email protected]:3306/digchouti?charset=utf8', max_overflow=5)#生成一個SQLORM基類,創(chuàng)建表必須繼承他,,別問我啥意思就是這么規(guī)定的Base = declarative_base()class Person(Base):    __tablename__ = 'userinfo'    id   = Column(Integer, primary_key=True)    name = Column(String(32))    def __repr__(self):        return '<Person(name='%s')>' % self.name此代碼是創(chuàng)建了一個名字叫userinfo的表,,表里有兩列,一列是id,,一列是name,。3、添加數(shù)據(jù)當(dāng)然我們創(chuàng)建了表,,肯定也要添加數(shù)據(jù),代碼如下:#創(chuàng)建一個person對象person = Person(name='張三')#添加person對象,,但是仍然沒有提交到數(shù)據(jù)庫session.add(person)#提交數(shù)據(jù)庫session.commit()當(dāng)然還能添加多條數(shù)據(jù):session.add_all([    Person(name='張三'),    Person(name='aylin')])session.commit()
4、查找數(shù)據(jù)在sqlalchemy模塊中,,查找數(shù)據(jù)給提供了query()的方法 下面我就把能用到的給列舉一下:
#獲取所有數(shù)據(jù)session.query(Person).all()#獲取name=‘張巖林’的那行數(shù)據(jù)session.query(Person).filter(Person.name=='張三').one()#獲取返回數(shù)據(jù)的第一行session.query(Person).first()#查找id大于1的所有數(shù)據(jù)session.query(Person.name).filter(Person.id>1).all()#limit索引取出第一二行數(shù)據(jù)session.query(Person).all()[1:3]#order by,按照id從大到小排列session.query(Person).ordre_by(Person.id)#equal/like/inquery = session.query(Person)query.filter(Person.id==1).all()query.filter(Person.id!=1).all()query.filter(Person.name.like('%ay%')).all()query.filter(Person.id.in_([1,2,3])).all()query.filter(~Person.id.in_([1,2,3])).all()query.filter(Person.name==None).all()#and orfrom sqlalchemy import and_from sqlalchemy import or_query.filter(and_(Person.id==1, Person.name=='張三')).all()query.filter(Person.id==1, Person.name=='張三').all()query.filter(Person.id==1).filter(Person.name=='張三').all()query.filter(or_(Person.id==1, Person.id==2)).all()# count計算個數(shù)session.query(Person).count()# 修改updatesession.query(Person).filter(id > 2).update({'name' : '張三'})# 通配符ret = session.query(Users).filter(Users.name.like('e%')).all()ret = session.query(Users).filter(~Users.name.like('e%')).all()# 限制ret = session.query(Users)[1:2]# 排序ret = session.query(Users).order_by(Users.name.desc()).all()ret = session.query(Users).order_by(Users.name.desc(), Users.id.asc()).all()# 分組from sqlalchemy.sql import funcret = session.query(Users).group_by(Users.extra).all()ret = session.query( func.max(Users.id), func.sum(Users.id), func.min(Users.id)).group_by(Users.name).all()ret = session.query( func.max(Users.id), func.sum(Users.id), func.min(Users.id)).group_by(Users.name).having(func.min(Users.id) >2).all()# 連表ret = session.query(Users, Favor).filter(Users.id == Favor.nid).all()ret = session.query(Person).join(Favor).all()ret = session.query(Person).join(Favor, isouter=True).all()# 組合q1 = session.query(Users.name).filter(Users.id > 2)q2 = session.query(Favor.caption).filter(Favor.nid < 2)ret = q1.union(q2).all()q1 = session.query(Users.name).filter(Users.id > 2)q2 = session.query(Favor.caption).filter(Favor.nid < 2)ret = q1.union_all(q2).all()
復(fù)制代碼

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點,。請注意甄別內(nèi)容中的聯(lián)系方式,、誘導(dǎo)購買等信息,謹防詐騙,。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多