时间:2022-12-29 10:52:16 | 栏目:Python代码 | 点击:次
前言
我们经常需要将大量数据保存起来以备后续使用,数据库是一个很好的解决方案。在众多数据库中,MySQL数据库算是入门比较简单、语法比较简单,同时也比较实用的一个。本文主要介绍了Python接入MySQL实现增删改查的相关内容,下面话不多说,一起来看看详细的介绍吧
打开数据库连接,创建数据库和表
基本语法如下:
execute(query, args=None) # query为字符串类型的sql语句 # args:可选的序列或映射,用于query的参数值。 # 如果args为序列,query中必须使用%s做占位符; # 如果args为映射,query中必须使用%(key)s做占位符
案例:数据库名learning,表名houses,字段name house_location purchasing_year
import pymysql db = pymysql.connect('localhost', 'root', "password") # 打开数据库连接,password替换为本机数据库密码 cursor = db.cursor() cursor.execute('drop database learning;') cursor.execute('create database learning;') cursor.execute('use learning') sql_create = """create table houses (name VARCHAR(100) NOT NULL, house_location VARCHAR(100) NOT NULL, purchasing_year VARCHAR(100) NOT NULL);""" cursor.execute(sql_create)
插入
# 插入 sql_insert = """insert into houses values(%s,%s,%s);""" cursor.execute(sql_insert,('梦璃','南天门',1995)) # 插入单条数据 cursor.executemany(sql_insert,[('紫英','蜀山',1996),('天河','石沉',1997),('菱纱','溪洞',1998)]) # 插入多条数据
查询
sql_select = """select * from houses""" # 单条查询 cursor.execute(sql_select) while 1: result = cursor.fetchone() if result is None: # 取完所有结果 break print(result) # 多条查询,取3条数据 cursor.execute(sql_select) Result = cursor.fetchmany(3) for res in Result: print(res) # 多条查询,取所有数据 cursor.execute(sql_select) Result = cursor.fetchall() for res in Result: print(res)
更新
# 更新一条数据 sql_update = """update houses set purchasing_year=2000 where name='菱纱';""" cursor.execute(sql_update) cursor.execute(sql_select) Result = cursor.fetchall() for res in Result: print(res) # 更新多条数据 sql_update = """update houses set purchasing_year=%s where name=%s;""" cursor.executemany(sql_update,[(2018,'梦璃'),(2019,'紫英')]) cursor.execute(sql_select) Result = cursor.fetchall() for res in Result: print(res) # 回滚事务 db.rollback() cursor.execute(sql_select) Result = cursor.fetchall() for res in Result: print(res)
删除
# 删除1条数据 sql_delete = """delete from houses where name='梦璃';""" cursor.execute(sql_delete) cursor.execute(sql_select) Result = cursor.fetchall() for res in Result: print(res) # 删除多条数据 sql_delete = """delete from houses where name=%s;""" cursor.executemany(sql_delete,[('天河'),('紫英')]) cursor.execute(sql_select) Result = cursor.fetchall() for res in Result: print(res)
关闭游标,关闭数据库连接
cursor.close() # 关闭游标 db.commit() db.close() # 关闭数据库连接 print('sql执行成功')
总结