python 连接 mysql 查询 数据 及 表结构

时间:2024-03-19 07:53:34

参考链接:
python 向 mysql 中 添加 数据
python 中自定义查询和修改 mysql 数据库内容

python 连接 mysql 查询 数据 及 表结构

第一步:连接到mysql数据库

import pymysql
conn = pymysql.connect(host='localhost',user='root',password='1234',db='ishop1',charset="utf8")

第二步:创建游标 对象

cursor = conn.cursor()   #cursor当前的程序到数据之间连接管道

第三步:组装sql语句

sql = 'select * from commodity'

第四布:执行sql语句

cursor.execute(sql)

第五步:处理结果集

获取一条数据

one = cursor.fetchone()
print(one)

结果:
python 连接 mysql 查询 数据 及 表结构
获取多条数据

many = cursor.fetchmany(3)
print(many)
#接着上面的查询,接着往下查询
many = cursor.fetchmany(3)
print(many)

结果:
python 连接 mysql 查询 数据 及 表结构
获取所有数据

all = cursor.fetchall()
for each in all:
    print(each)

结果:
python 连接 mysql 查询 数据 及 表结构
查询表的结构

fields = cursor.description
print(fields)

结果:
python 连接 mysql 查询 数据 及 表结构
查询字段名

head = []
for field in fields:
    head.append(field[0])
print(head)

python 连接 mysql 查询 数据 及 表结构

第六步:关闭所有的连接

#关闭游标
cursor.close()
#关闭数据库
conn.close()

总代码如下:

import pymysql
import json
#第一步:连接到mysql数据库
conn = pymysql.connect(host='localhost',user='root',password='1234',db='ishop1',charset="utf8")
#第二步:创建游标  对象
cursor = conn.cursor()   #cursor当前的程序到数据之间连接管道

# 第三步:组装sql语句
sql = 'select * from commodity'

#第四部:执行sql语句
cursor.execute(sql)

#第五步:处理结果集
#获取一条数据
one = cursor.fetchone()
print(one)
#获取多条数据
many = cursor.fetchmany(3)
print(many)
#接着上面的查询,接着往下查询
many = cursor.fetchmany(3)
print(many)

#获取所有数据
all = cursor.fetchall()
for each in all:
    #print(json.dumps(each,ensure_ascii=False))#拒绝显示rscII码
    #print(type(each),each)
    print(each)

#查询表的结构
fields = cursor.description
for i in fields:
    print(i)

#查询字段名
head = []
for field in fields:
    head.append(field[0])
print(head)

#第六步:关闭所有的连接
#关闭游标
cursor.close()
#关闭数据库
conn.close()