pymysql的使用

import pymysql


def insertsql():
connection_sql = pymysql.connect(
# 要写localhost不写127.0.01
host='localhost', # 自己主机地址
port=3306, # 端口号
user='root', # 用户名
password='123', # 密码
db='many-to', # 数据库名
charset='utf8' # 编码方式
)
# 获取游标
# 让返回的数据是一个字典 以一个键值对 pymysql.cursors.DictCursor
cursor = connection_sql.cursor(pymysql.cursors.DictCursor)
str1 = '1',
str2 = '1.70'
# 写sql语句
sql = 'select * from user where id > %s and height < %s'
print(sql)

try:
# 执行sql语句 [str1, str2] 是上面的参数 多个得用[]列表
cursor.execute(sql, [str1, str2])
# 获取查询所有的数据
a = cursor.fetchall()
print(a)
connection_sql.commit()
except Exception as e:
connection_sql.rollback()
raise e
# # try 里面的代码有错误就进入这里
# else:
# pass
# # 无论 上面什么结果都执行这里
# finally:
# pass
# 关闭游标
cursor.close()
# 关闭连接
connection_sql.close()

# 调用函数
insertsql()

posted on 2021-06-15 15:28  晴天,  阅读(79)  评论(0)    收藏  举报