使用python连接mysql进行单表查询
方法一:python 3.6+pymysql
1、导入pymysql,并创建数据库连接
import pymysql
# 使用python连接mysql数据库,并对数据库进行增删改查操作
# 创建连接,数据库主机地址host 数据库用户名称user 密码password 数据库名database 数据库端口port 数据库字符集编码charset
conn = pymysql.connect(host='127.0.0.1',
user='root',
password='123456',
database='empdb',
port=3307,
charset='utf8')
print("连接成功")
2、创建游标
# 创建游标 cursor =conn.cursor()
3、获取单条数据cursor.fetchone()
# 使用cursor.fetchones()返回的是单个元组 # 一次获取一条数据
# 使用cursor.fetchones()返回的是单个元组
# 一次获取一条数据
def sqlfetchones():
select_emp_sql = "SELECT * FROM empdb.employee"
# 执行sql
cursor.execute(select_emp_sql)
data_fetchone = cursor.fetchone()
print(data_fetchone)
4、获取单条数据cursor.fetchall()
# 使用cursor.fetchall()返回的是多个元组 # 获得所有数据
# 使用cursor.fetchall()返回的是多个元组
# 获得所有数据
def sqlfetchall():
select_emp_sql = "SELECT * FROM empdb.employee"
# 执行sql
cursor.execute(select_emp_sql)
data_fetchall = cursor.fetchall()
print(data_fetchall)
5、 关闭游标,关闭连接
# 关闭游标 cursor.close() # 关闭连接 conn.close()
完整代码:
import pymysql
# 创建连接,数据库主机地址 数据库用户名称 密码 数据库名 数据库端口 数据库字符集编码
conn = pymysql.connect(host='127.0.0.1',
user='root',
password='123456',
database='empdb',
port=3307,
charset='utf8')
print("连接成功")
# 创建游标
cursor =conn.cursor()
# 使用cursor.fetchones()返回的是单个元组
# 一次获取一条数据
def sqlfetchones():
select_emp_sql = "SELECT * FROM empdb.employee"
# 执行sql
cursor.execute(select_emp_sql)
data_fetchone = cursor.fetchone()
print(data_fetchone)
# 使用cursor.fetchall()返回的是多个元组
# 获得所有数据
def sqlfetchall():
select_emp_sql = "SELECT * FROM empdb.employee"
# 执行sql
cursor.execute(select_emp_sql)
data_fetchall = cursor.fetchall()
print(data_fetchall)
def closeconn():
# 关闭游标
cursor.close()
# 关闭连接
conn.close()
sqlfetchall()
sqlfetchones()
运行结果:
方法二:python 3.6+pymysql+pandas
pd.read_sql()的方式读取数据库
import pymysql
import pandas as pd
# 创建连接,数据库主机地址 数据库用户名称 密码 数据库名 数据库端口 数据库字符集编码
conn = pymysql.connect(host='127.0.0.1',
user='root',
password='123456',
database='empdb',
port=3307,
charset='utf8')
print("连接成功")
# 查询数据
def selectsql1():
select_emp_sql = "SELECT * FROM empdb.employee"
data = pd.read_sql(select_emp_sql,conn)
print(data)
return data
selectsql1()
# 关闭连接
conn.close()
运行结果:



