Python中有自帶且方便使用的數據庫模塊——dbm模塊,直接Import使用,無需在Settings中導入。
dbm模塊的主要方法介紹。
1.打開數據庫方式
例如:with dbm.open('dataDB', 'c') as my_DB_1:pass
- r:默認只讀。
- w:讀寫方式打開現有的數據庫。
- c:讀寫方式,數據庫不存在則創建。
- n:讀寫方式,創建一個新的空數據庫。
2.數據的寫入、刪除、讀取和查找方法
- 寫入數據:d[key]=data
- 刪除數據:del d[key]
- 讀取數據:data=d[key] 或 data=d.get(key,defaultvalue)
- 查找數據:flag=key in d
注:dataDB,d是數據庫名稱。
# NoSQL數據庫:dbm模塊
import dbm
try:
with dbm.open('dataDB', 'c') as my_DB_1:
# 寫入數據。
my_DB_1['name'] = '張三'
my_DB_1['age'] = '18'
# 讀取數據。
# 字節序列。
print('字節序列:', my_DB_1['name'])
# decode():轉換爲字符串。
print('name:', my_DB_1['name'].decode())
print('age:', my_DB_1['age'].decode())
# 讀取age鍵數據,設置默認值爲字節序列:b'18'。
# print('age:', int(my_DB_1.get('age', b'18').decode()))
# print(int(my_DB_1.get('a',b'20').decode()))
# 判斷是否存在age數據
if 'age' in my_DB_1:
my_DB_1['age'] = '20'
print('update_age:', my_DB_1['age'].decode())
else:
print('Data does not exist.')
# 刪除數據
del my_DB_1['name']
print('name:', my_DB_1['name'].decode())
except Exception as e:
print('執行失敗:', e)
執行結果:
Python也可以用通過導入pymysql連接使用MySQL。
import pymysql
try:
# 打開數據庫連接 主機地址 端口號默認3306 用戶名 密碼 數據名 字符集
db = pymysql.Connect(host='localhost', port=3360, user='root', passwd='123456', db='opt_a', charset='utf8')
# 創建一個遊標對象
cursor = db.cursor()
# 創建表
sql = ' create table student(id int not null,name varchar(20),age int )'
# 添加數據
add_sql = "insert into student(id,name,age) value (2,'zhangsan',12)"
# 查詢語句
select1_sql = "select * from student where id='1'"
select2_sql = "select * from student"
# 更新語句
update_sql = "update student set age=age+1 where age=13"
# # 刪除語句
delect_sql = "delete from student where id=2"
# 執行sql語句
# cursor.execute(sql)
cursor.execute(add_sql)
cursor.execute(select1_sql)
cursor.execute(select2_sql)
cursor.execute(update_sql)
cursor.execute(delect_sql)
# 獲取一條數據"
data1 = cursor.fetchone()
# 獲取所有的數據
data2 = cursor.fetchall()
# print('data1:',data1)
# print('data1[0]:',data1[0])
# print('data2:', data2)
db.commit() # 提交事務: 一個事務就是一個不可分割的整體,事務中的操作要麼都執行,要麼都不執行。
db.close()
print('運行成功.')
except Exception as e:
db.rollback() # 回滾 所有操作都不提交。
print('運行失敗:', e)