备忘python对mysql数据库操作的方法
个人建议:
获取数据库的数据时, 如果要对数据进行计算与分析, 建议使用pandas的read_sql方法, 生成的数据更适合计算;
写入数据库时, 如果是经常性的、部分数据引入, 建议使用MySQLdb的写入方法; 如果是大量的、需要一次性引入的数据, 建议使用pandas的to_sql方法引入
安装MySQLdb安装whl
在whl文件夹中, 按住shift键, 并在空白处点击鼠标右键, 点击在此处打开PowerSell窗口;
输入命令:pip install mysqlclient-1.4.5-cp37-cp37m-win_amd64.whl回车
提示successfully则ok
引入模块cmd> python
python> import MySQLdb
查询数据库import MySQLdb,MySQLdb.cursors
# 连接数据库
db = MySQLdb.connect(host='IP地址',user='用户名',passwd='密码',db='数据库名',port='端口',charset='utf8',cursorclass = MySQLdb.cursors.DictCursor)
# cursorclass = MySQLdb.cursors.DictCursor 返回字典格式的数据
# 使用cursor()方法获取操作游标 ?什么是游标?
cursor = db.cursor()
# sql语句
sql = 'SHOW TABLES'
cursor.execute(sql)
# 获取一条记录fetchone() 获取所有记录fetchall()
data = cursor.fetchone()
print ('data:',data)
db.close()
写入数据库(REPLACE)REPLACE简单理解为: 如果要写入的数据中, 在数据库中已经存在相同主键(ID), 则先执行删除,然后执行插入;import MySQLdb
# 准备数据
list = [['1','2','3'],['3','4','5']] # 此处如果最外层是元组, 则cursor.executemany(sql,list)
# 连接数据库
db = MySQLdb.connect(host='IP地址',user='用户名',passwd='密码',db='数据库名',port='端口',charset='utf8')
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 执行sql语句
sql = 'REPLACE INTO LIVE (列1,列2,列3) \
VALUES (%s,%s,%s)'
try:
# 执行sql语句
cursor.executemany(sql,tuple(list))
# 提交到数据库执行
db.commit()
except:
# 发生错误时回滚
db.rollback()
db.close()