Python对MySQL进行增删查改
python连接MySQL数据库:pymysql
# 测试操作
import pymysql # 打开数据库
db = pymysql.connect("localhost", "root", "test1234", "pythontest", charset='utf8' )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 使用execute执行sql语句
cursor.execute("select * from user")
data = cursor.fetchall()
print(data)
db.close()
数据库user表:

User类:
class User:
def __init__(self, id, username, birth_data, money, father, mother):
self.id = id
self.username = username
self.birth_data = birth_data
self.money = money
self.father = father
self.mother = mother
def set_username(self, name):
self.username = name
def get_username(self):
return self.username
def set_money(self, money):
self.money = money
def get_money(self):
return self.money
def print(self):
if self.father == None:
# print("id:", self.id, " father= NULL mother=NULL")
print("id: {} username: {} father= NULL mother= NULL".format(self.id, self.username))
else:
# print("id:", self.id, " father=", self.father.username, " mother=", self.mother.username)
print("id: {} username: {}".format(self.id, self.username))
增删查改:
# 增删查改
from Practice_Recode.UserTest.User import User
import pymysql def openDb():
global db, cursor
db = pymysql.connect("localhost", "root", "test1234", "pythontest", charset='utf8')
cursor = db.cursor() def closeDb():
db.close() # 按照用户id查询用户记录(输出相应内容,并返回查到的user对象)
def serarchDb(id):
openDb()
sql = "select * from user where id = " + str(id)
rst = cursor.execute(sql)
if rst == 0:
# print("查找失败")
return None
else:
# print("查找成功")
data = cursor.fetchone()
# print(data)
user1 = User(data[0], data[1], data[2], int(data[3]), data[4], data[5])
return user1
closeDb() # 按照用户id删除用户记录
def deleteDb(id):
openDb()
sql = "delete from user where id = " + str(id)
rst = cursor.execute(sql)
if rst == 0:
print("删除失败")
else:
print("删除成功")
closeDb() # 新增用户
def insertDb(user1):
openDb()
sql = "insert into user values('%d','%s','%s','%d','%s','%s')" % (
user1.id, user1.username, user1.birth_data, user1.money, user1.father, user1.mother)
# "INSERT INTO mytb(title,keywd) VALUES('%s','%s')"%(x,y)
cursor.execute(sql)
db.commit()
closeDb() # 更新用户信息
def updateDb(user1):
openDb()
sql = "update user set username = '%s', money='%d' where id='%d'" % (user1.username, user1.money, user1.id)
# update user set username='C', money=9999 where id=5;
rst = cursor.execute(sql)
if rst == 0:
print("更新失败")
else:
print("更新成功")
closeDb() # 测试数据
# testuser = serarchDb(5)
# testuser.set_username('C')
# testuser.set_money(9082)
# # print(testuser.id, testuser.username, testuser.money, testuser.father, testuser.mother)
# updateDb(testuser) # user1 = User(5, "c", "1111-03-11", 10000, father='A', mother='a')
# insertDb(user1)
# user2 = User(0, "d", "1111-03-11", 10000, 'A', 'a') # 自增键id设置为0,新增时即可实现自增
# insertDb(user2) # user2 = User(1, "A", "1111-03-11", 10000, father=None, mother=None)
# user3 = User(2, "a", "1111-03-11", 10000, father=None, mother=None)
# user1 = User(3, "B", "1111-03-11", 10000, user2, user3)
# user1.dayin()
# user1.father.dayin()
查找某个用户的祖辈:
# 查找当前user所有的亲缘关系
# father,monther,father's father,fahter's mother from Practice_Recode.UserTest.test02 import *
import pymysql def openDb():
global db, cursor
db = pymysql.connect("localhost", "root", "test1234", "pythontest", charset='utf8')
cursor = db.cursor() def closeDb():
db.close() # 查找所有用户id,并返回ids,users
def serarchDbAll():
openDb()
ids = []
users = []
sql = "select * from user"
rst = cursor.execute(sql)
if rst == 0:
# print("查找失败")
return None
else:
# print("查找成功")
data = cursor.fetchall()
for i in range(len(data)):
user = User(0, "", "", 0, "", "")
user.id = data[i][0]
user.username = data[i][1]
user.birth_data = data[i][2]
user.money = data[i][3]
user.father = data[i][4]
user.mother = data[i][5]
users.append(user)
ids.append(data[i][0])
closeDb()
return ids, users # 根据名字返回这个人用户对象(未考虑重名问题)
def NameSearchUser(name):
ids, users = serarchDbAll()
for user in users:
if user.username == name:
return user
return None # 找某用户的爸爸用户
def searchFa(user):
if user.father != None:
fauser = NameSearchUser(user.father) # 根据爸爸的名字返回爸爸用户
if fauser != None:
print("他的名字是:", fauser.username)
return fauser
print("他的名字为空")
return None # 找某用户的妈妈用户
def searchMo(user):
if user.mother != None:
mouser = NameSearchUser(user.mother) # 根据名字返回妈妈用户
if mouser != None:
print("她的名字是:", mouser.username)
return mouser
print("她的名字为空")
return None # 查找13号的祖先
currentuser = serarchDb(13) # 得到13号用户本人
print("当前用户是:", currentuser.username) print("当前用户的父亲是:")
cur_fa = searchFa(currentuser) # 得到当前用户的父亲
print(cur_fa) print("当前用户的母亲是:")
cur_mo = searchMo(currentuser) # 得到当前用户的母亲
print(cur_mo) print("当前用户的爷爷:")
cur_fa_fa = searchFa(cur_fa) # 得到当前用户的爷爷
print(cur_fa_fa) print("当前用户的奶奶:")
cur_fa_mo = searchMo(cur_fa) # 得到当前用户的奶奶
print(cur_fa_mo) print("当前用户的姥爷:")
cur_mo_fa = searchFa(cur_mo) # 得到当前用户的姥爷
print(cur_mo_fa) print("得到当前用户的姥姥:")
cur_mo_mo = searchMo(cur_mo) # 得到当前用户的姥姥
print(cur_mo_mo)
Python对MySQL进行增删查改的更多相关文章
- Mysql常用增删查改及入门(二)
常用:数据库常用就是DML:增删查改 1.增加数据: insert into 表名 values (值1,值2...); insert into 表名 (字段1,字段2) values (值1,值2) ...
- day03 Python字典dict的增删查改及常用操作
字典是python中唯一的映射类型,采用键值对(key-value)的形式存储数据.python对key进行哈希函数运算,根据计算的结果决定value的存储地址,所以字典是无序存储的,且key必须是可 ...
- VisualStudio 连接 MySql 实现增删查改
首先创建数据库,建立一个用户登录表 2.visualStudio默认是不支持MySql的,要想通过Ado.Net 操作MySql 需要在管理NeGet包添加对MySql.Data 和 MySql.D ...
- 后端Spring Boot+前端Android交互+MySQL增删查改(Java+Kotlin实现)
1 前言&概述 这篇文章是基于这篇文章的更新,主要是更新了一些技术栈以及开发工具的版本,还有修复了一些Bug. 本文是SpringBoot+Android+MySQL的增删查改的简单实现,用到 ...
- nodejs连接mysql并进行简单的增删查改
最近在入门nodejs,正好学习到了如何使用nodejs进行数据库的连接,觉得比较重要,便写一下随笔,简单地记录一下 使用在安装好node之后,我们可以使用npm命令,在项目的根目录,安装nodejs ...
- php mysql增删查改
php mysql增删查改代码段 $conn=mysql_connect('localhost','root','root'); //连接数据库代码 mysql_query("set na ...
- node.js+mysql增删查改
数据库和表: -- -- 数据库: `test` -- -- -------------------------------------------------------- -- -- 表的结构 ` ...
- PHP与MYSQL结合操作——文章发布系统小项目(实现基本增删查改操作)
php和mysql在一起几十年了,也是一对老夫老妻了,最近正在对他们的爱情故事进行探讨,并做了一个很简单的小东西——文章发布系统,目的是为了实现mysql对文章的基本增删查改操作 前台展示系统有:文章 ...
- mysql 增删查改
非关系型数据库关系型数据库Oracle mysql sqlserver db2 Postgresql Sqlite access sqlserver 微软db2 ibm================ ...
随机推荐
- 多测师讲解_ 高级自动化测试selenium_001基本学习
高级自动化测试python+selenium教程手册 --高级讲师肖sir 第 1 章webdriver 环境搭建好了,我们正式学习 selenium 的 webdriver 框架,它不像 QTP 之 ...
- element中过滤器filters的使用(开发小记)
之前在开发过程中遇到这么一个问题,一串数据需要在el-table中展示,其中含有金额字段,需要将其转换成标准数据格式,即三位一个逗号间隔. 今年刚毕业就上手项目了,第一次接触的Vue,开发经验少,也忘 ...
- MeteoInfoLab脚本示例:AIRS Grid HDF数据
AIRS Grid HDF数据是HDF4 EOS格式,数据地理坐标信息可以被MeteoInfo自动识别,脚本程序更为简单.需要注意的是读取数据时Y轴是反向的(卫星数据通常如此).脚本程序: #Add ...
- shell脚本获取随机数
$RANDOM系统变量 在bash中,支持$RANDOM系统变量,范围是 [0, 32767] #!/bin/bash set -e randN() { local N=$1 echo $(($RAN ...
- centos8下启用rc-local服务
一,centos8不建议写rc.local,默认启动时执行的命令放到何处? 以前我们会把linux开机执行的命令写入到/etc/rc.local 在centos8上系统不再建议我们写入到rc.loca ...
- composer使用git作为仓储
composer.json "repositories": [ { "type":"git", "url":" ...
- jq ajax封装
//ajax公共方法,zs 2017-06-14 $.extend({ //比jq的ajax多了的参数: //salert是否在请求成功后弹出后台的SuressStr字段值 //ealertStr:请 ...
- Disconnected from the target VM, address: '127.0.0.1:1135', transport: 'socket'-SpringBoot启动报错
一.问题由来 本地代码在一次打包后,再次启动项目时报了一个错误,详细的错误信息如下: 2020-10-23 15:10:26.724 [] [main] INFO o.s.c.a.Annotation ...
- 对于72种常用css3的使用经验
对于72种常用css3的使用经验 保存网站源码 目的 保证有足够的css和js文件源码 拿到当前网页的整体布局 本地化 创建web项目 将web项目创建出来 在项目中创建一个文件夹 将所有的js和cs ...
- image restoration(IR) task
一般的,image restoration(IR)任务旨在从观察的退化变量$y$(退化模型,如式子1)中,恢复潜在的干净图像$x$ $y \text{} =\text{}\textbf{H}x\tex ...