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)