MySQL数据库:python操作MySQL

python操作MySQL


一、pymysql模块

1.pymysql基本操作

import pymysql
# 1 连接MySQL服务端
# connect是一个类,其返回值是一个对象,需要用一个变量名来接收
conn = pymysql.connect(
host='127.0.0.1', # 回送地址
port=3306, # 端口
user='root', # mysql用户名
passwd='root123', # mysql密码
db='db3', # 选择数据库
charset='utf8mb4', # 指定字符编码
# 自动提交关于增、删、改操作
)
"""
由于增、删、改、查中,查只读的一个操作的等级比较低,所有不需要二次确认,
而增、删、改的写入的操作,权限等级比较高,所有需要commit()方法来二次确认
而在连接服务端时候,用autocommit自动提交则不需要二次确认
"""
# 2 产生游标对象
# 当 obj.cursor()内没有参数的时候,默认返回的列表内是元组
cursor = conn.cursor()
"""
(('t1',), ('t2',), ('t3',), ('t4',), ('t5',), ('t6',), ('t7',), ('t8',))
"""
# 当填写参数时候,则返回的列表内是字典,字典的键是字段名
# cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
"""
[{'Tables_in_db3': 't1'}, {'Tables_in_db3': 't2'}, {'Tables_in_db3': 't3'}, {'Tables_in_db3': 't4'}, {'Tables_in_db3': 't5'}, {'Tables_in_db3': 't6'}, {'Tables_in_db3': 't7'}, {'Tables_in_db3': 't8'}]
"""
# 3 编写SQL语句
sql = 'show tables'
# 4 发送SQL语句
# execute的返回值为收SQL语句影响的行数
affect_rows = cursor.execute(sql)
print(affect_rows) # 8
# 5 获取SQL语句执行之后的结果
res = cursor.fetchall()
print(res)

2.增删改查

import pymysql
# 连接mysql,输入root账户和密码
conn = pymysql.connect(
host='127.0.0.1',
port=3306, user='root',
passwd='root123',
db='db4',
charset='utf8'
)
# 产生游标对象
cursor = conn.cursor() # 括号内不填写额外参数 数据是元组 指定性不强 [(),()]
"""
指定参数为 列表内套字典 [{},{}]
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
"""
# 1 新增
# execute也有返回值 接收的是SQL语句影响的行数
cursor.execute("create database db4 default charset utf8 collate utf8_general_ci")
conn.commit()
# 2 查看数据库
cursor.execute("show databases")
cursor.execute("use db4")
# 查看数据表
cursor.execute("show tables")
result = cursor.fetchall()
conn.commit()
# 3 删除数据库db4
cursor.execute("drop database db4")
conn.commit()
# 4 用mysql查看其中的数据表
cursor.execute("use mysql")
cursor.execute("show tables")
res = cursor.fetchall()
print(res) # (('columns_priv',), ('db',), ('engine_cost',), ('event',), ('func',), ('general_log',), ('gtid_executed',), ('help_category',), ('help_keyword',), ('help_relation',), ...
# 5 关闭连接
cursor.close()
conn.close()

二、pymysql补充说明

1.获取数据

关键字 作用
fetchall() 获取所有的结果
fetchone() 获取结果集的第一个数据
fetchmany() 获取指定数量的结果集

2.增删改查

关键字 作用
autocommit=True connect添加配置,增 删 改 操作时自动确认
conn.commit() 增 删 改 操作时手动添加代码确认

三、注册登录

1.注册

import pymysql
def register():
print('用户注册')
# 1 获取用户输入
username = input('请输入用户名:').strip()
pwd = input('请输入密码:').strip()
# 2 获取用户连接mysql数据库
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root123', charset='utf8', db='usersdb')
cursor = conn.cursor()
# 3 编写sql语句
sql_statement = "insert into users(name,password) values('{}','{}') ".format(username, pwd)
# 4 连接mysql执行sql语句
cursor.execute(sql_statement)
conn.commit()
# 5 关闭数据库连接
cursor.close()
conn.close()
print('注册成功')

2.登录

def login():
print('用户登录')
# 1 获取用户信息
username = input('请输入用户名:')
pwd = input('请输入密码:')
# 2 连接mysql服务端
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root123', db='usersdb')
cursor = conn.cursor()
# 3 编写sql语句
# sql_statement = "select * from users where name='{}' and password='{}'".format(username, pwd)
sql_statement = "select * from users where name='%s' and password='123'" % (username)
# sql_statement = "select * from users where name='' or 1=1 -- ' and password='123'"
# 4 执行sql语句
cursor.execute(sql_statement)
# cursor.execute("select * from users where name=%s and password=%s", [username, pwd])
# 5 获取结果
res = cursor.fetchone()
# 6 断开与mysql的连接
cursor.close()
conn.close()
# 7 判断返回的信息
if res:
print('登录成功', res)
else:
print('登录失败', res)

注意:SQL注入的问题

posted @   Duosg  阅读(75)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示