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================ ...
随机推荐
- 111 01 Android 零基础入门 02 Java面向对象 04 Java继承(上)02 继承的实现 01 继承的实现
111 01 Android 零基础入门 02 Java面向对象 04 Java继承(上)02 继承的实现 01 继承的实现 本文知识点: 继承的实现 说明:因为时间紧张,本人写博客过程中只是对知识点 ...
- Apache HttpClient 4.5 在Springboot中使用
ConnectionRequestTimeout httpclient使用连接池来管理连接,这个时间就是从连接池获取连接的超时时间,可以想象下数据库连接池 ConnectTimeout 连接建立时间, ...
- 从零开始学python之Python安装和环境配置
Python 3适用于Windows,Mac OS和大多数Linux操作系统.即使Python 2目前可用于许多其他操作系统,有部分系统Python 3还没有提供支持或者支持了但被它们在系统上删除了, ...
- 搭建单机版的kafka
搭建单机版的kafka
- MySQL数据库之索引、事务、存储引擎详细讲解
一.索引 1.1 索引的概念 索引是一个排序的列表,存储着索引值和这个值所对应的物理地址 无须对整个表进行扫描,通过物理地址就可以找到所需数据 (数据库索引类似书中的目录,通过目录就可以快速査找所需信 ...
- HTML CSS+JS想要做放大镜练习,如何获取同样的大图和小图?
1.进入某商城找到对应的图片: 步骤一: 步骤二: 步骤三: 2.检查源代码: 情况一:按F12 情况二:鼠标在网页内,直接右键-->"检查元素" 1.选中选择部分 2.点击 ...
- 浅谈Samsung Exynos4412处理器
转载于:http://www.cnblogs.com/android210/archive/2013/01/16/2862349.html Topic:浅谈Samsung Exynos4412处理器( ...
- linux 线程挂起恢复
1 //============================================================================ 2 // Name : thread. ...
- 题解:[COCI2011-2012#5] BLOKOVI
题解:[COCI2011-2012#5] BLOKOVI Description PDF : https://hsin.hr/coci/archive/2011_2012/contest5_tasks ...
- 【C语言学习笔记】空间换时间,查表法的经典例子!知识就是这么学到的~
我们怎么衡量一个函数/代码块/算法的优劣呢?这需要从多个角度看待.本篇笔记我们先不考虑代码可读性.规范性.可移植性那些角度. 在我们嵌入式中,我们需要根据实际资源的情况来设计我们的代码.比如当我们能用 ...