python调用数据库判断_python 访问数据库 笔记
1 使用dbm持久字典
存儲名稱、值對,保存在磁盤上,鍵和值都必須是字符串類型
不同dbm模塊創建的文件是不兼容的。如果使用某個dbm模塊創建一個dbm持久字典,那么必須使用相同的模塊來讀取數據。
dbm 選擇最好的dbm模塊,dbm模塊替自己做出選擇,在創建一個新的持久字典時,dbm模塊將選擇系統上已有的最好的實現方式。
dbm.dumb使用dbm庫的一個簡單但可移植的實現
dbm.gnu使用GNU dbm庫
所有dbm模塊都支持使用open函數創建一個新的dbm對象。打開后便可以在字典中存儲數據、讀取數據、關閉dbm對象 以及相關聯的數據文件、移除項和檢查字典中是否存在某個鍵等。
c 打開數據文件以便對其進行讀寫,必要時創建該文件;
N打開文件以便對其進行讀寫,但總是創建一個新的空文件。如果該文件已經存在,則將被覆蓋,已有的內容將會丟失
W打開文件以便對其進行讀寫,但是如果該文件不存在,那么不會創建它。
import dbm
db=dbm.open('websites','c')
#add an item.
db['www.python.org']='python home page'
print(db['www.python.org'])
#close and save to disk.
db.close()
dbm模塊可能創建多個文件,通常一個文件用于數據,一個文件用于鍵的索引
通常底層的dbm庫將為數據附加一個后綴 如:.dat
dbm模塊的open方法返回一個新的dbm對象,之一便可以使用此對象存儲和檢索數據。
鍵和值都必須是字符串,如果希望保存一個對象,可以使用pickle模塊對它進行串行化
close方法關閉文件,并將數據保存到磁盤中。
可以將open函數返回的對象視作一個字典對象。value=db['key']
可以使用del刪除字典中值:del db['key']
keys 方法返回包含所有鍵的一個列表 for key in db.keys():
如果在文件中包含大量的鍵,那么keys方法的執行可以會占用很長時間。另外對于較大的文件 ,此方法可能需要大量的內存來存儲列表
import dbm
#open existing file
db=dbm.open('websites','w')
#add another item
db['www.wrox.com']='wrox home page'
#verify the previous item remains.
if db['www.python.org']!=None:
print('found www.python.org')
else:
print('error:mission item')
# iterate over the keys .may be slow.
#may use a lot of memory
for key in db.keys():
print("key=",key,"value=",db[key])
del db['www.wrox.com']
print("after deleting www.wrox.com,we have:")
for key in db.keys():
print('key=%s value=%s'%(key,db[key]))
#close and save to disk.
db.close() # 關閉字典,保存所有修改到硬盤上。
當數據需求可以通過存儲一些鍵、值對來滿足時,dbm模塊十分有用。數據需求簡單、存儲少量的數據時使用
一些dbm庫對可以用于值的空間總數進行了限制,有時達到最大值即1024字節
如果需要支持事務、復雜的數據結構或多個連接數據的表,使用關系數據庫
2 使用關系數據庫
使用python DB AP訪問數據庫時,必須首先創建一些Sql語句。
Sqlite數據庫隨python一起安裝、簡單、輕便、實用。
import os
import sqlite3
conn=sqlite3.connect('sample_database') #每個數據庫模塊都有一個連接函數,返回一個connection對象
cursor=conn.cursor() #游標,是一種python 對象,用于使用數據庫
#create tables
#cursor.execute("""drop table if exists user""") #這里刪除的判斷與下面創建重復 execute 執行sql語句
#cursor.execute("""drop table if exists employee""")
#cursor.execute("""drop table if exists department""")
#cursor.execute("""drop index if exists userid""")
#cursor.execute("""drop index if exists emplid""")
#cursor.execute("""drop index if exists deptid""")
#cursor.execute("""drop index if exists deptfk""")
#cursor.execute("""drop index if exists mgr""")
#cursor.execute("""drop index if exists emplid""")
#cursor.execute("""drop index if exists deptmgr""")
cursor.execute("""
create table if not exists employee (empid integer,
firstname varchar,
lastname varchar,
dept integer,
manager integer,
phone varchar)""")
cursor.execute("""
create table if not exists department( departmentid integer,
name varchar,
manager integer)""")
cursor.execute("""
create table if not exists user(userid intege,
username varchar,
employeeid integer)""")
#create indices.
cursor.execute("""create index if not exists userid on user(userid)""")
cursor.execute("""create index if not exists emplid on employee(empid)""")
cursor.execute("""create index if not exists deptid on department(departmentid)""")
cursor.execute("""create index if not exists deptfk on employee(dept)""")
cursor.execute("""create index if not exists mgr on employee(manager)""")
cursor.execute("""create index if not exists emplid on user(employeeid)""")
cursor.execute("""create index if not exists deptmgr on department(manager)""")
conn.commit() # 提交事務以將所有的修改保存到數據庫中
cursor.close()? # 當腳本完成時,關閉游標和連接以釋放資源
conn.close()
Sqlite具有自身的API
在?https://wiki.python.org/moin/DatabaseInterfaces
下載對應的數據庫模塊,并安裝
python3 -m pip install mysql-connector
insertdata.py
import os
import sqlite3
conn=sqlite3.connect('sample_database')
cursor=conn.cursor()
#create employees
cursor.execute("""
insert into employee(empid,firstname,lastname,manager,dept,phone)
values(1,'Eric','Foster-Johnson',1,1,'555-5555')""")
cursor.execute("""
insert into employee(empid,firstname,lastname,manager,dept,phone)
values(2,'Peter','Tosh',2,3,'555-5554')""")
cursor.execute("""
insert into employee(empid,firstname,lastname,manager,dept,phone)
values(3,'Bunny','Wailer',2,2,'555-5553')""")
#create departments.
cursor.execute("""
insert into department(departmentid,name,manager)
values(1,'development',1)""")
cursor.execute("""
insert into department(departmentid,name,manager)
values(2,'qa',2)""")
cursor.execute("""
insert into department(departmentid,name,manager)
values(3,'operations',2)""")
#create users.
cursor.execute("""
insert into user(userid,username,employeeid)
values(1,'ericfj',1)""")
cursor.execute("""
insert into user(userid,username,employeeid)
values(2,'ericfj',2)""")
cursor.execute("""
insert into user(userid,username,employeeid)
values(3,'ericfj',3)""")
conn.commit()
cursor.close()
conn.close()
simplequery.py
import os
import sqlite3
conn=sqlite3.connect('sample_database')
cursor=conn.cursor()
cursor.execute("""
select e.firstname,e.lastname,d.name
from employee e inner join department d on e.dept=d.departmentid
order by e.lastname desc """)
for row in cursor.fetchall(): #數據存儲到cursor對象中,可以使用fetchall方法提取這些數據,也可以用fetchone方法一次獲取一行
print(row)# 這些數據顯示python的元組
cursor.close()
conn.close()
import os
import sqlite3
conn=sqlite3.connect('sample_database')
cursor=conn.cursor()
username1="bunny"
query="""
select u.username,e.firstname,e.lastname,m.firstname,m.lastname,d.name
from user u,employee e,employee m,department d
where u.employeeid=e.empid
and e.manager=m.empid
and e.dept=d.departmentid
and u.username=?
"""
cursor.execute(query,(username1,))
#cursor.execute(query)
for row in cursor.fetchall():
(username,firstname,lastname,mgr_firstname,mgr_lastname,dept)=row
#print(row)
name=firstname+" "+lastname
manager=mgr_firstname+" "+mgr_lastname
print("%s:%s,managed by %s in %s"%(username,name,manager,dept))
#cursor.execute("update user set username=? where userid=?",("peter",2))
#cursor.execute("update user set username=? where userid=?",("bunny",3))
#conn.commit()
#cursor.execute("select * from user")
#for r in cursor.fetchall():
# print(r)
cursor.close()
conn.close()
sqlite3.connect(database)如果指定的數據庫不存在,則創建一個數據庫,可以指定帶路徑的文件名,在其他地方創建數據庫
cursor.execute(sql[,optional parameters])sqlite3模塊支持兩種類型的占位符:問號和命名占位符
cursor.execute("insert into people values(?,?)",(who,age)) 元組參數列表
cursor.executescript(sql_script) 收到腳本會執行多個sql語句,用分號分隔
connection.total_changes()返回數據庫連接打開以來被修改、插入或刪除的數據庫總行數
connection.commit() 提交當前的事務
connection.rollback()回滾更改
connection.close()關閉數據庫連接
cursor.fetchone()返回一行結果,當沒有數據時返回 None
cursor.fetchmany([size=cursor.arraysize]) 返回結果集中的下一行組,由size參數指定的一個列表
cursor.fetchall()獲取所有行,返回一個列表 ,沒有可用的行時,返回一個空的列表
可以利用cursor對象的definition屬性查看返回數據的信息。
3 使用mysql connector
>>> mydb=mysql.connector.connect(host='localhost',user='root' ,passwd='123')
>>> mycursor=mydb.cursor()
>>> mycursor.execute("show databases")
>>> for x in mycursor:
print(x)
('information_schema',)
('mysql',)
('performance_schema',)
('sakila',)
('sys',)
('testmysql',)
('testwin',)
('world',)
>>>
import mysql.connector
mydb=mysql.connector.connect(host='localhost',user='root',passwd='123',database='testwin')
mycursor=mydb.cursor()
mycursor.execute("show tables")
for r in mycursor:
print(r)
mydb.commit()
mycursor.close()
mydb.close()
sql= "INSERT INTO sites (name, url) VALUES (%s, %s)"val= ("RUNOOB", "https://www.runoob.com")
mycursor.execute(sql, val)
sql= "INSERT INTO sites (name, url) VALUES (%s, %s)"val= [('Google', 'https://www.google.com'), ('Github', 'https://www.github.com'), ('Taobao', 'https://www.taobao.com'), ('stackoverflow', 'https://www.stackoverflow.com/')]mycursor.executemany(sql, val)
print(mycursor.rowcount, "記錄插入成功。")
sql= "SELECT * FROM sites WHERE name = %s"na= ("RUNOOB", )mycursor.execute(sql, na)myresult= mycursor.fetchall()
sql= "UPDATE sites SET name = %s WHERE name = %s"val= ("Zhihu", "ZH")mycursor.execute(sql, val)
4 處理錯誤
Warning 用于非致命的問題。必須定義為StandardError的子類
Error 所有錯誤的基類。必須定義為StandardError的子類
InterfaceError用于數據庫模塊中的錯誤,而不是數據庫本身的錯誤。必須定義為Error的子類
DatabaseError用于數據庫中的錯誤。必須定義為Error的子類
DataError DatabaseError的子類,指數據中的錯誤
OperationalError DatabaseError的子類,指那些類似于丟失數據庫連接 錯誤。這些錯誤一般在python腳本設計者的控制之外
IntegrityError DatabaseError的子類,用于可能破壞關系完整性的情況,例如唯一性約束或外鍵約束。
InternalError DatabaseError的子類,指數據庫模塊內部的錯誤,例如游標未被激活
ProgrammingError DatabaseError的子類,指那些類似于錯誤的表名稱等由程序員造成的問題
NotSupportedError DatabaseError的子類,指試圖調用不支持的功能
5 檢查模塊的功能和元數據
DB API 定義了幾個需要在模塊級別定義的全局變量。可以使用這些全局變量確定關于數據庫模塊的信息以及它所支持的一些特征。
Apilevel 對于DB API2.0 應該保存 2.0
Paramstyle 定義了在Sql語句中,如何顯示動態數據的占位符
qmark 使用問號
numeric 使用一種位置數字的方式 ”:1“、” :2“
named 使用冒號和每個參數的名稱 如:name
format 使用ANSI C Sprintf格式代碼 如:對于字符串使用%s ,對于整數使用%d
pyformat 使用python 的擴展格式代碼 如:%(name)s
import importlib
def get_paramstyle(conn):
name=conn.__class__.__module__.split('.')[0]
mod=importlib.import_module(name)
return mod.paramstyle
import sqlite3
conn=sqlite3.connect('sample_database')
styletest=get_paramstyle(conn)
print (styletest)
小結:
數據庫為數據的存儲提供了一種方便的手段。可以使用一些附加的模塊編寫能夠訪問所有主流數據庫的python腳本。
dbm模塊 持久化一個字典。
connection 對象封裝了到數據庫的一個連接。使用數據庫模塊的connect函數以得到一個新的連接。傳遞給connect函數的各個參數可能會因各個模塊的不同而不同。
游標提供了用于與數據庫進行交互的主要對象。使用connection對象以獲得一個游標。游標可以執行一些sql語句
可以將動態數據作為一個包含若干值的元組傳遞給游標的 execute方法
在執行了一個查詢操作之后,cursor對象對數據進行保存。使用fetchone 或fetchall方法都可以提取數據
在對數據庫進行修改之后,調用connection對象的commit方法以提交事務并保存更改。使用rollback方法可以撤消更改。
當操作完成后,調用每個游標的close方法,當不需要連接時,調用connection對象的close方法
DBAPI定義了一個異常集合。python腳本應該對這些異常進行檢查,以處理可能出現的各種問題
疑問:sqlite3物理地址,在哪里可以看到?怎么樣查看數據庫、表 結構?
總結
以上是生活随笔為你收集整理的python调用数据库判断_python 访问数据库 笔记的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何得到iterator的当前元素_链表
- 下一篇: 堆排序时间复杂度_堆排序算法