python代码操作MySQL

发布时间 2023-09-27 05:55:06作者: 我来改变代码
  • 普通连接方式:
# pip install pymysql
import pymysql

#1.创建链接对象
mysql_conn = pymysql.Connect(
    host = 'localhost',  # 服务器地址
    port = 3306,
    user = 'root',
    password = '',  # 密码为空
    database = 'spider_py',
    charset='utf8')
try:
  #创建一个游标对象
  cursor = mysql_conn.cursor()
  #2.增加记录操作
  sql = 'insert into emp(name,sex,age,dep_id)values("%s","%s",%d,%d)'%('haha','female',20,200)
  re = cursor.execute(sql)
  mysql_conn.commit() #对数据进行整改后,记得进行事物的提交
  print('完成录入:',re)
except Exception as e:
    print('失败了:', e)
    if cursor:
        cursor.close()
    # 报错,回滚
    mysql_conn.rollback()
try:
  #3.删除记录
  sql = 'delete from emp where name = "%s"'%'haha'
  # print(sql)
  re = cursor.execute(sql)
  mysql_conn.commit()
  print('完成录入:', re)
except Exception as e:
    print('失败了:', e)
    if cursor:
        cursor.close()
    # 报错,回滚
    mysql_conn.rollback()


try:
    #4.修改操作
    new_age = input('enter a new age:')
    # new_age = int(new_age)
    sql = 'update emp set age = %d where id = 3'%new_age
    # print(sql)
    re = cursor.execute(sql)
    mysql_conn.commit()
    print('完成录入:', re)
except Exception as e:
    print('失败了:', e)
    if cursor:
        cursor.close()
    # 报错,回滚
    mysql_conn.rollback()

#查询操作
sql = 'select * from emp where age > 30'
cursor.execute(sql) #负责执行sql语句
#fetchall返回的是一个元组,元组元素又为一个元素,该元组中存储的是查询到的一条记录
# all_data = cusor.fetchall() #获取查询到所有的数据,如果没有查询到数据返回一个空元组
# print(all_data)
# 可根据re_num分多次获取1个数据,写多个fetchone或者fetchmany(N)
# one_data = cursor.fetchone() #fetchone只会返回查询到的第一条数据;如果没有查询到数据返回None
result = cursor.fetchmany(3)
# print(result)
for re in result:
    print(re)

#关闭打开的资源对象
cursor.close()
mysql_conn.close()

  • 连接池:防止频繁连接和关闭连接服务器。(常用)
# pip install dbutils
import pymysql
from dbutils.pooled_db import PooledDB
from pymysql.cursors import DictCursor
POOL = PooledDB(
    creator=pymysql,  # 使用链接数据库的模块
    maxconnections=10,  # 连接池允许的最大连接数,0和None表示不限制连接数
    mincached=2,  # 初始化时,链接池中至少创建的空闲的链接,0表示不创建
    maxcached=5,  # 链接池中最多闲置的链接,0和None不限制
    blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
    setsession=[],  # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
    ping=0,
    host='localhost', port=3306, user='root', passwd='', charset="utf8", db='spider_py'
)
conn = POOL.connection()
cursor = conn.cursor(cursor=DictCursor)	# DictCursor数据为字典格式
cursor.execute("select * from user where token=%s", [str,])
result = cursor.fetchone()
cursor.close()
conn.close()  # 不是关闭连接,将此连接交还给连接池

  • 知识点:数据库操作
-- 增加数据insert into+表格名(列名) values(要增加的数据)
INSERT INTO table_name(col1, col2, col3...) values (val1,val2,val3)

-- 删除数据delete from+表格名 where+条件;
Delete from table_name		-- 全表删
Delete from table_name where 'col+条件,如:COLUMN=value'

-- 修改数据update+表格名 set+要更新的内容  where+条件
UPDATE table_name SET col1 = val1, col2 = val2... where clause

-- 查询数据select+要查询的内容 from+表格名 where+条件;
-- 条件,包括=、!=、<、>;模糊查询:_一位字符串、%多位字符
SELECT sname (as '名字') FROM student;
select * from table_name wehre col1+条件1 and/or col2+条件2; 
SELECT * FROM student WHERE sname LIKE 'lee%';

-- 分组查询 ,先分组后计算;聚合函数:AVG()、max()、min()、count()计数
#对group by后的列进行分组
select 列名,要计算的内容 from table_name where 查询条件 group by 列名; 
#先分组、计算后筛选
SELECT class_name,AVG(sage) FROM student GROUP BY class_name HAVING AVG(sage) >20;

-- 排序
SELECT * FROM student ORDER BY sage ASC;	-- 升序(ASC可不写,默认)
SELECT * FROM student ORDER BY sage DESC;	-- 降序

--分页查询limit后加开始位置,数几个;0,可不写
SELECT * FROM student LIMIT 0,3;

  • 跳过授权表重置密码的方法
    你可以将mysq1获取用户名和密码校验的功能看成是一个装饰器装饰在了客户端请求访问的功能上
    我们如果将该装饰器移除 那么mysq1服务端就不会校验用户名和密码了
# 1 先关闭当前mysq1服务端
命令行的方式启动(让mysq1跳过用户名密码验证功能)mysq1d --skip-grant-tables
# 2 直接以无密码的方式连接
mysql -uroot -p 直接回车
# 3 修改当前用户的密码
update mysq.user set password=password(123456) whereuser='root' and host='1ocalhost';
'''
真正存储用户表的密码字段 存储的肯定是密文只有用户自己知道明文是什么 其他人都不知道 这样更加的安全密码比对也只能比对密文
'''
#4立刻将修改数据刷到硬盘
flush privileges;
#5 关闭当前服务端 然后以正常校验授权表的形式启动

  • mysql配置文件修改:统一编码格式;和免输入管理员账号密码
在my.ini文件中进行如下配置
[mysq1d]
character-set-server=utf8
collation-server=utf8—genera1—ci
[cIient]
defau1t-character-set=utf8
[mysq1]
user="root"
password=123456
defau1t-character-set=utf8