Python学习18-连接数据库
2018-08-20 本文已影响248人
残阳夕露

查看所有Python相关学习笔记
本文包含内容
- 连接mysql数据库
- 连接db2数据库
连接mysql数据库
安装相关库
# 此处指定mysqlclient版本为1.3.12
pip3 install mysqldb==1.3.12
python中连接mysql数据库
import MySQLdb
# 设置参数
connection = MySQLdb.connect\
(host = 'xx.xx.xx.xx', # 指定ip
user = 'root', # 用户名
passwd = '1qaz@WSX', # 密码
db = 'plesson', #连接的库
charset = 'utf8' # 指定数据库对应的编码
)
c = connection.cursor() # 建立游标
c.execute('select * from sq_course') # 注释sql,查询
查询数据
- sql格式
# 查询全表数据
select * from 表名;
# 查询符合条件的数据
select * from 表名 where id =7 and name='dd';
# 查询符合条件的数据的id
select id from 表明 where id =7;
- 返回最近一次操作的行数
numrows = c.rowcount # 返回最近一次操作到的行数
print(numrows)
-
获取数据
单步执行获取数据
fetchone,fetchmany,fetchall
- 获取单行
for x in range(numrows): # 返回的是一个元组 row= c.fetchone() # 获取单行 print(row) # 执行结果 (1, 'Python', 'Python基础与实战', 1) (2, 'Selenium', 'web自动化', 2)
- 获取多行数据(可指定行数)
fetchmany(n)
类似于切片:查询到到结果[:n] (默认显示一行数据)
data = c.fetchmany(2) # 获取多行(可指定行数) print(data) data = c.fetchmany(1) # 获取多行(可指定行数) print(data) # 执行结果 ((1, 'Python', 'Python基础与实战', 1), (2, 'Selenium', 'web自动化', 2)) ((1, 'Python', 'Python基础与实战', 1),)
- 获取所有数据
datas = c.fetchall() # 获取所有数据 print(datas) # 执行结果 ((1, 'Python', 'Python基础与实战', 1), (2, 'Selenium', 'web自动化', 2))
插入数据
- sql格式:
insert into 表名 values(值1,值2...);
insert into 表名(列1,列2...) values(值1,值2...);
- 执行插入操作时记得要提交
commit
c.execute("insert into sq_course values(7,'dddddd','dddd','2')")
connection.commit() #提交
print(f'插入数据的行数:{c.rowcount}') # 查询插入了多少条数据
# 执行结果
插入数据的行数:1
删除数据
- sql格式:
# 删除符合条件的数据
delete from 表名 where xxx ;
# 删除整张表内的数据
delete from 表名 ;
- 执行删除操作时记得要提交
commit
# 删除id=7的数据
c.execute("delete from sq_course where id=7")
connection.commit() #提交
print(f'删除数据的行数:{c.rowcount}')
# 执行结果
删除数据的行数:1
修改数据
- sql格式:
# 更新整张表的数据
update 表名 set 列名1=值1;
# 更新符合条件的数据
update 表名 set 列名1=值1,列名2=值2 where id=7;
- 执行修改操作时记得要提交
commit
c.execute("update sq_course set name='dddd' where id=7")
connection.commit() #提交d
print(f'修改数据的行数:{c.rowcount}')
# 执行结果
修改数据的行数:1
关闭数据库的连接
connection.close()
问题汇总
启动教管系统服务时报错django.db.utils.OperationalError: (1193, "Unknown system variable 'storage_engine'")
> mysql server 5.7
- 更改setting文件中的相关配置
# 原配置
"OPTIONS":{"init_command":"SET storage_engine=INNODB;"}
# 更改后的配置
"OPTIONS":{"init_command":"SET default_storage_engine=INNODB;"}
- mac无法安装mysqlclient
参考文章
修改mysql_config时如果提示没有权限,可以通过which mysql_config找到该文件,右键查看简介,修改权限为“读与写”,文件内容修改后,再改为“只读”。
连接db2数据库
# coding=utf-8
import ibm_db,traceback
class Db2Jyrs():
def __init__(self,mobile):
self.mobile = mobile
self.infos = {
'duanxin' :
{'pingtai':'短信',
'DATABASE':'name1', # 数据库
'HOSTNAME':'xx.xx.xx.xx', # ip
'PORT':50000,
'PROTOCOL':'TCPIP',
'UID':'user1', # 用户名
'PWD':'password1' # 密码
},
'guanwei' :
{'pingtai':'官微',
'DATABASE':'name2', # 数据库
'HOSTNAME':'xx.xx.xx.xx', # ip
'PORT':50000,
'PROTOCOL':'TCPIP',
'UID':'user1', # 用户名
'PWD':'password2' # 密码
}
}
def db2_conn(self,sql,info='duanxin'):
infomation = self.infos[info]
print(f".........................{infomation['pingtai']}................................")
conn = ibm_db.connect(f"DATABASE={infomation['DATABASE']};"
f"HOSTNAME={infomation['HOSTNAME']};"
f"PORT=50000;PROTOCOL=TCPIP;"
f"UID={infomation['UID']};"
f"PWD={infomation['PWD']};","","")
if conn:
stmt = ibm_db.exec_immediate(conn, sql)
if info == 'duanxin':
result = ibm_db.fetch_both(stmt)
ibm_db.close(conn)
return result
else:
ibm_db.close(conn)
return
def deteleInfo(self):
sql_02=f"delete FROM 表名 where MOBILE_PHONE = '{self.mobile}';"
try:
self.db2_conn(sql_02,info='guanwei')
except:
print(f'unkown:\n{traceback.format_exc()}')
else:
print('已清除')
finally:
print('执行完毕')
def getinfo(self):
sql_01 = f"select * from 表名 where mobile='{self.mobile}'\
order by id desc\
fetch first 1 rows only;"
result = self.db2_conn(sql_01, info='duanxin')
if result:
print(f"{result['MOBILE']}\n{result['ADD_TIME']}\n{result['CONTENT']}\n")
else:
print('无记录')
if __name__ == '__main__':
aa = Db2Jyrs('13460151001')
aa.getinfo()
# aa.deteleInfo()