SQLite是一種嵌入式數(shù)據(jù)庫,,SQLite本身是C寫的體積很小,它的數(shù)據(jù)庫就是一個文件,,所以經(jīng)常被集成到各種應(yīng)用程序中,,甚至在iOS和Android的App中都可以集成,。Python內(nèi)置了sqlite3。 #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ā)現(xiàn)Python里封裝的數(shù)據(jù)庫操作很簡單: 如果SQL語句帶有參數(shù),,那么需要把參數(shù)按照位置傳遞給cursor.execute()方法,,有幾個?占位符就必須對應(yīng)幾個參數(shù),示例: cursor.execute('select * from user where name=? ', ['abc']) 二、Mysql db = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='Geek_Web', charset='utf8mb4') db = pymysql.connect(root,root, Geek_Web) config = { # 在連接數(shù)據(jù)庫時候加上 cursorclass 就可以數(shù)據(jù)庫內(nèi)容以字典格式返回 #!/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) 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 db = pymssql.connect(host='192.0.0.200',user='ymyg',password='ymyg',database='Geek_Web') 4. PyMssql 返回字典數(shù)據(jù) db = pymssql.connect(host='192.0.0.200',user='ymyg',password='ymyg',database='Geek_Web',as_dict=True) 5.連接示例 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í)行完成:') 5. PyMssql 參數(shù) connect() 參數(shù)
操作方法
其他方法
四、Oracle 連接Oracle比MySQL麻煩一些,,連接Oracle需要安裝cx_Oracle和oracle客戶端 1. 安裝 cx_Oracle 庫 2. Oracle instant client 下載安裝 3. 連接數(shù)據(jù)庫的幾種方法 db = cx_Oracle.connect('root/root@localhost: 1523/orcl') db = cx_Oracle.connect('root', 'root', 'localhost: 1523/orcl') makedsn(IP/HOST, PORT, TNSNAME) 5. PyMssql 返回字典數(shù)據(jù) cx_Oracle 的 Cursor 對象有一個屬性 rowfactory 是是用來自定義查詢結(jié)果的預(yù)處理方法的,,定義一個閉包 def makedict(cursor): 6.連接示例 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() # -*- 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(); 五,、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 SQLAlchemy 六、Peewee Peewee中 也就是說,,一個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)建表,。 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)建表了
其中,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,。 # 指定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)容如下:
操作數(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()刪除。
3,、改若是,,已經(jīng)添加過數(shù)據(jù)的的實例或查詢到的數(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ù),。
七,、SQLAlchemy 使用 sqlalchemy 有3種方式: 通過 engine = create_engine('dialect+driver://username:password@host:port/database')初始化連接
例如 常用的數(shù)據(jù)庫連接字符串 # postgresql # mysql # oracle sqlalchemy訪問數(shù)據(jù)庫的示例 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框架也可以提供兩個對象之間的一對多, 多對多功能. 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() |
|