Python操作MySQL

    xiaoxiao2023-10-06  170

    需要先安装pymysql模块,安装方法pip install pymysql

    pymysql在连接数据库的时候会有一个自动提交参数autocommit,一般情况下,oracle数据库本身默认不设置自动提交(或设置自动提交为false),mysql数据库本身默认设置自动提交(或设置自动提交为true)。一般情况下,不管哪种数据库,都可以在代码里不设置自动提交为true或false(不主动connection.setAutoCommit(bool)),可在代码每次主动commit之前,判断该数据库本身是否设置自动提交,若数据库本身已设置自动提交,则无需手动通过代码commit,不然就会报错;若数据库本身未设置自动提交,则需通过代码主动commit,方能使本次数据库操作生效,如下:

    conn.commit()

    插入表数据:

    import pymysql # 连接数据库 conn = pymysql.connect(host="localhost", user='root', password='root', db='zhifou', port=3306, charset='utf8') #port及charset尽量加上,utf8不要写成utf-8,mysql的默认端口是3306,默认输出tuple数据 # 利用连接对象获取游标对象 cur = conn.cursor() # 插入表数据 # cur.execute("insert into type (name, sort) values(%s, %s)", ("测试", "99")) #插入一条数据 cur.executemany("insert into type (name, sort) values(%s, %s)", (("ceshi1", "100"), ("ceshi2", "101"), ("ceshi3", "102"), ("ceshi4", "103"))) #插入多条数据

    查询表数据:

    # 查询表数据 cur.execute("select * from type") lines = cur.fetchall() #返回所有查询结果 for line in lines: print(line) print(cur.fetchone()) #返回一条查询结果,结果为None,因为游标已经在表的底部了 cur.execute("select * from type") #必须重新查询 print(cur.fetchone()) #显示第一条记录 data = cur.fetchmany(2) #返回指定数量的查询结果,注意此处没有重新查询,游标在第一条数据之后 for i in data: #结果为第2、3条数据 print(i)

    结果为:

    (40, '测试', 99) (41, 'ceshi1', 100) (42, 'ceshi2', 101) (43, 'ceshi3', 102) (44, 'ceshi4', 103) None (40, '测试', 99) (41, 'ceshi1', 100) (42, 'ceshi2', 101)

    移动游标: relative模式:从当前位置下移一个位置

    cur.scroll(1) #默认mode="relative",游标位置从第三条数据下方移动到第四条数据下方

    结果为:

    (44, 'ceshi4', 103)

    absolute模式:从结果集的第一行下移一个位置

    cur.scroll(1, mode="absolute") print(cur.fetchone())

    结果为:

    (41, 'ceshi1', 100)

    上移一个位置:

    cur.scroll(-1) #从当前位置(第二条数据下方)上移一个位置(第一条数据下方) print(cur.fetchone())

    结果为:

    (41, 'ceshi1', 100)

    输出字典型数据:

    # 方法一: conn = pymysql.connect(host="localhost", user='root', password='root', db='zhifou', port=3306, charset='utf8', cursorclass=pymysql.cursors.DictCursor) #输出字典型数据,此处用cursorclass cur = conn.cursor() # 方法二: # conn = pymysql.connect(host="localhost", user='root', password='root', db='zhifou', port=3306, charset='utf8') # cur = conn.cursor(cursor=pymysql.cursors.DictCursor) #此处用cursor cur.execute("select * from type") lines = cur.fetchall() for line in lines: print(line)

    结果为:

    {'id': 40, 'name': '测试', 'sort': 99} {'id': 41, 'name': 'ceshi1', 'sort': 100} {'id': 42, 'name': 'ceshi2', 'sort': 101} {'id': 43, 'name': 'ceshi3', 'sort': 102}

    修改表数据:

    cur.execute("update type set name=%s where id=40", ("ceshi0")) cur.scroll(0, mode='absolute') #返回数据集的第一条数据 print(cur.fetchone())

    结果为:

    (40, 'ceshi0', 99)

    删除表数据:

    cur.execute("delete from type where id=41") cur.execute("delete from type where id>39")

    最后记得关闭游标和数据库连接:

    cur.close() #先关闭游标,防止占用资源 conn.close() #关闭数据库连接
    最新回复(0)