python读写mysql数据库
方法一:
1. python连接mysql数据库:需要用到 pymysql 库和 sqlalchemy库:
import pandas as pd
from sqlalchemy import create_engine
import pymysql
创建连接 create_engine:
con_engine = create_engine('mysql+pymysql://username:passwd@localhost:3306/database_name')
# 示例:
# con_engine = create_engine('mysql+pymysql://root:123456@localhost:3306/database_name')
# username:数据库用户名,例如 root
# passwd:密码,例如 123456
# localhost:host主机地址,例如:127.0.0.1
# 3306:是数据库的端口,一般是3306,但是也可能改变
# database_name:数据库名
con_engine = create_engine('mysql+pymysql://username:passwd@localhost:3306/database_name?charset=utf8') #需要时也可用
2. 提供 sql 语句
sql_ = "select * from table_name;" #table_name某个表名
3. 执行查询,使用 read_sql_query 得到pandas的dataframe数据
df_data = pd.read_sql_query(sql_, con_engine)
xxx = df['key_words'].tolist()
print(xxx)
4. 写数据到 mysql 数据库
#写两列数据,建立dataframe格式数据
df_write = pd.DataFrame({'id_py':[1,2,3,4],'name_py':['Tom','Bob','Cathy','Jack']})
df_write.to_sql('table_py', con_engine, index = False) # index = False表示不加索引列,写到table_py表,如果表已经存在,会报错:ValueError: Table 'table_py' already exists.
方法二:使用 read_sql
# username = 'root'
# passwd = '123456'
# database_name = 'db_test'
con_engine = pymysql.connect(host = 'localhost' ,user = username, password = passwd, database = database_name, port=3306, charset = 'utf8') #通过参数形式传递,参数是字符串形式
sql_ = "select * from table_name;" #table_name某个表名
df_data = pd.read_sql(sql_ , con_engine)
方法三:直接使用pymysql进行查询,插入数据、更新数据、删除数据等修改数据表的操作需要添加 commit 和 rollback 语句
import pymysql # 建立数据库连接,username, passwd, database_name都是如上,预先定义的参数,localhost也可以替换成某个数据库的ip地址
con_engine = pymysql.connect(host = 'localhost' ,user = username, password = passwd, database = database_name, port=3306, charset = 'utf8') # 使用cursor()方法获取游标
cursor = con_engine.cursor() # SQL语句
sql_ = "select * from table_name;"
try:
# 执行SQL语句
cursor.execute(sql_)
# fetchall()获取所有记录,形成的是元组,results = cursor.fetchmany(10)获取前10条,results = cursor.fetchone()获取一条数据
results = cursor.fetchall()
for row in results: #依次获取每一行数据
id_ = row[0] #第1列
key_words_ = row[1]
type_words_ = row[2]
address_name_ = row[3]
# 打印结果
print(id_,key_words_,type_words_,address_name_)
except:
print ("Error: unable to fetch data") # 关闭数据库连接
con_engine.close()
例如删除操作:
import pymysql # 建立数据库连接,username, passwd, database_name都是如上,预先定义的参数,localhost也可以替换成某个数据库的ip地址
con_engine = pymysql.connect(host = 'localhost' ,user = username, password = passwd, database = database_name, port=3306, charset = 'utf8') # 使用cursor()方法获取游标
cursor = con_engine.cursor() # SQL语句
sql_ = "delete * from table_name where id > 5;"
try:
# 执行SQL语句
cursor.execute(sql_)
con_engine.commit() #提交修改,类似github的commit操作
except:
con_engine.rollback() #不成功则回滚 # 关闭数据库连接
con_engine.close()
参考:
https://www.jianshu.com/p/238a13995b2b
https://blog.csdn.net/luoluopan/article/details/100074959
https://www.runoob.com/python3/python3-mysql.html
python读写mysql数据库的更多相关文章
- 使用python将mysql数据库的数据转换为json数据
由于产品运营部需要采用第三方个推平台,来推送消息.如果手动一个个键入字段和字段值,容易出错,且非常繁琐,需要将mysql的数据转换为json数据,直接复制即可. 本文将涉及到如何使用Python访问M ...
- Python操作Mysql数据库时SQL语句的格式问题
一.概述 近日使用Python对Mysql数据库进行操作,遇到SQL语句死活出问题的情况.由于最初没有将异常打印出来,一直不知道原因.随后,将异常打印出来之后,通过异常信息,对代码进行修改.最终,成功 ...
- python使用mysql数据库
一,安装mysql 如果是windows 用户,mysql 的安装非常简单,直接下载安装文件,双击安装文件一步一步进行操作即可. Linux 下的安装可能会更加简单,除了下载安装包进行安装外,一般的l ...
- python操作mysql数据库的相关操作实例
python操作mysql数据库的相关操作实例 # -*- coding: utf-8 -*- #python operate mysql database import MySQLdb #数据库名称 ...
- shell中读写mysql数据库
本文介绍了如何在shell中读写mysql数据库.主要介绍了如何在shell 中连接mysql数据库,如何在shell中创建数据库,创建表,插入csv文件,读取mysql数据库,导出mysql数据库为 ...
- python 连接Mysql数据库
1.下载http://dev.mysql.com/downloads/connector/python/ 由于Python安装的是3.4,所以需要下载下面的mysql-connector-python ...
- Windows下安装MySQLdb, Python操作MySQL数据库的增删改查
这里的前提是windows上已经安装了MySQL数据库,且配置完成,能正常建表能操作. 在此基础上仅仅需安装MySQL-python-1.2.4b4.win32-py2.7.exe就ok了.仅仅有1M ...
- python对mysql数据库操作的三种不同方式
首先要说一下,在这个暑期如果没有什么特殊情况,我打算用python尝试写一个考试系统,希望能在下学期的python课程实际使用,并且尽量在此之前把用到的相关技术都以分篇博客的方式分享出来,有想要交流的 ...
- 使用python操作mysql数据库
这是我之前使用mysql时用到的一些库及开发的工具,这里记录下,也方便我查阅. python版本: 2.7.13 mysql版本: 5.5.36 几个python库 1.mysql-connector ...
随机推荐
- 学习使用Lombok生成代码
一.介绍 Lombok官网:https://projectlombok.org/ Lombok的功能简单一点说,就是可以帮我们生成一些代码,这些代码并不是在源码(source code)体现出来的,而 ...
- LeetCode_443. String Compression
443. String Compression Easy Given an array of characters, compress it in-place. The length after co ...
- [LeetCode] 59. Spiral Matrix II 螺旋矩阵 II
Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order. For ...
- [LeetCode] 270. Closest Binary Search Tree Value 最近的二叉搜索树的值
Given a non-empty binary search tree and a target value, find the value in the BST that is closest t ...
- [LeetCode] 741. Cherry Pickup 捡樱桃
In a N x N grid representing a field of cherries, each cell is one of three possible integers. 0 mea ...
- 2017ACM/ICPC广西邀请赛 1007 Duizi and Shunzi
Duizi and Shunzi Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) ...
- TCP/IP协议的工作流程
1.在源主机上,应用层将一串应用数据流向下传输给传输层 2.传输层将应用数据截流成分组,并加上TCP报头形成TCP段,向下递交给网络层 3.在网络层给TCP段加上包括源主机,目的主机IP地址的IP报头 ...
- 一个php将数据库的数据导出到excle表格中的小dome
首先我们需要下载个PHPExcel,PHPExcel下载地址链接:https://pan.baidu.com/s/1nxpAc45 密码:qgct 下面来写个dome: <?php //把数据写 ...
- IP核——RAM
一.Quartus 1.打开Quartus ii,点击Tools---MegaWizard Plug-In Manager 2.弹出创建页面,选择Creat a new custom megafunc ...
- localhost-startStop-1启动失败
背景:在IDEA调试程序的时候,应用起不来,看日志是从main线程切换到localhost-startStop-1线程就开始卡住了 方法一 原因 这个问题和jvm上的熵池策略有关 解决 将$JAVA_ ...