一、mysql 交互
1.1 下载pymysql
pip install pymysql
1.2 导入pymysql
# import 导入
# pymysql 第三方模块名 用于链接mysql
import pymysql
1.3 让虚拟机端口转发 (使用本地mysql redis不需要这一步)
image.png
image.png
1.4 连接配置信息
我们会将配置信息用字典的形式存到 变量db_confing进行保存
- host : ip 地址
- port: 端口
- user:用户
- password:密码
- db:连接那个数据库
- charset:编码格式
db_confing = {
'host': '127.0.0.1',
'port': 3306,
'user': 'feihong',
'password': '123456',
'db': 'feihong',
'charset': 'utf8',
}
1.5 建立数据库连接
- pymysql.connect() 是 PyMySQL 库提供的一个函数,用于创建与数据库的连接对象。
- **db_config 是一种特殊的语法,用于将一个字典(dict)解包成关键字参数传递给函数。
# 通过pymysql 中的 connect(传入连接参数)方法获取到数据库对象
数据库对象 = pymysql.connect(**db_confing)
# 执行结果:
<pymysql.connections.Connection object at 0x0000024282DC74D0>
1.6 创建游标对象
什么游标对象?
通过数据库对象的cursor方法 就能获取到游标对象
游标对象 用于查询和操作数据库中的数据
# 创建游标对象
# 通过数据库对象的cursor方法 就能获取到游标对象
游标对象 = 数据库对象.cursor()
1.7 执行sql语句查询
# 写 查询的sql语句
sql = 'SELECT * FROM hk' # 写好sql语句
# 使用游标的execute方法执行sql语句
游标对象.execute(sql)
# 通过游标对象的fetchall方法 进行数据接收 把结果存在变量 返回结果中
返回结果 = 游标对象.fetchall()
# 可以打印result 拿到元组数据
prit(返回结果)
# 或者可以 通过
for row in 返回结果:
print(row)
# 关闭游标对象和数据库对象连接
游标对象.close()
数据库对象.close()
mysql全部代码
import pymysql
db_confing = {
'host': '127.0.0.1',
'port': 3306,
'user': 'feihong',
'password': '123456',
'db': 'feihong',
'charset': 'utf8',
}
# 建立数据库连接
数据库对象 = pymysql.connect(**db_confing)
# 创建游标对象
游标对象 = 数据库对象.cursor()
实战
英文版 变量名都是英文
# 执行SQL查询
sql = 'SELECT * FROM hk' # 写好sql语句
游标对象.execute(sql) # 执行sql语句
# 获取查询结果 fetchall
返回结果 = 游标对象.fetchall()
print(返回结果)
for row in 返回结果:
print(row)
# 修改表中的数据commit提交
# sql = 'insert into hk value(null,"真好",18)';
# 数据库对象.commit()
# 关闭游标和连接
数据库对象.close()
游标对象.close()
实战
- 英文变量
import pymysql
db_confing = {
'host': '127.0.0.1',
'port': 3306,
'user': 'ps',
'password': '123456',
'db': 'feihong',
'charset': 'utf8',
}
# 连接数据库 并存到变量conn中
conn = pymysql.connect(**db_confing)
# 创建游标对象
cursor = conn.cursor()
# 查询方法
def select():
# 写插入的sql语句
sql = 'select * from hk'
# 执行sql语句
cursor.execute(sql)
# 获取查询结果 fetchall
result = cursor.fetchall()
# 打印结果
print(result)
# 插入方法
def insert():
id = input('请输入你得id:')
name = input('请输入你得名字:')
age = input('请输入你的年龄:')
# 写插入的sql语句 # 需要用%s 来占位
sql = 'insert into hk value(%s,%s,%s)'
# 执行sql语句 execute 执行sql语句 并传参
cursor.execute(sql, (id, name, age))
# 提交
conn.commit()
insert()
- 中文变量
import pymysql
db_confing = {
'host': '127.0.0.1',
'port': 3306,
'user': 'ps',
'password': '123456',
'db': 'feihong',
'charset': 'utf8',
}
# 连接数据库 并存到变量conn中
数据库对象 = pymysql.connect(**db_confing)
# 创建游标对象
游标对象 = 数据库对象.cursor()
def select():
# 写插入的sql语句
sql = 'select * from hk'
# 执行sql语句
游标对象.execute(sql)
# 获取查询结果 fetchall
result = 游标对象.fetchall()
# 打印结果
print(result)
def insert():
id = input('请输入你得id:')
name = input('请输入你得名字:')
age = input('请输入你的年龄:')
# 写插入的sql语句 # 需要用%s 来占位
sql = 'insert into hk value(%s,%s,%s)'
# 执行sql语句 execute 执行sql语句 并传参
游标对象.execute(sql, (id, name, age))
# 提交
数据库对象.commit()
insert()
select()