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进行增删查改的更多相关文章

  1. Mysql常用增删查改及入门(二)

    常用:数据库常用就是DML:增删查改 1.增加数据: insert into 表名 values (值1,值2...); insert into 表名 (字段1,字段2) values (值1,值2) ...

  2. day03 Python字典dict的增删查改及常用操作

    字典是python中唯一的映射类型,采用键值对(key-value)的形式存储数据.python对key进行哈希函数运算,根据计算的结果决定value的存储地址,所以字典是无序存储的,且key必须是可 ...

  3. VisualStudio 连接 MySql 实现增删查改

    首先创建数据库,建立一个用户登录表 2.visualStudio默认是不支持MySql的,要想通过Ado.Net 操作MySql 需要在管理NeGet包添加对MySql.Data  和 MySql.D ...

  4. 后端Spring Boot+前端Android交互+MySQL增删查改(Java+Kotlin实现)

    1 前言&概述 这篇文章是基于这篇文章的更新,主要是更新了一些技术栈以及开发工具的版本,还有修复了一些Bug. 本文是SpringBoot+Android+MySQL的增删查改的简单实现,用到 ...

  5. nodejs连接mysql并进行简单的增删查改

    最近在入门nodejs,正好学习到了如何使用nodejs进行数据库的连接,觉得比较重要,便写一下随笔,简单地记录一下 使用在安装好node之后,我们可以使用npm命令,在项目的根目录,安装nodejs ...

  6. php mysql增删查改

    php mysql增删查改代码段 $conn=mysql_connect('localhost','root','root');  //连接数据库代码 mysql_query("set na ...

  7. node.js+mysql增删查改

    数据库和表: -- -- 数据库: `test` -- -- -------------------------------------------------------- -- -- 表的结构 ` ...

  8. PHP与MYSQL结合操作——文章发布系统小项目(实现基本增删查改操作)

    php和mysql在一起几十年了,也是一对老夫老妻了,最近正在对他们的爱情故事进行探讨,并做了一个很简单的小东西——文章发布系统,目的是为了实现mysql对文章的基本增删查改操作 前台展示系统有:文章 ...

  9. mysql 增删查改

    非关系型数据库关系型数据库Oracle mysql sqlserver db2 Postgresql Sqlite access sqlserver 微软db2 ibm================ ...

随机推荐

  1. P4107 [HEOI2015]兔子与樱花 贪心

    题目描述 传送门 分析 一道贪心题 首先我们可以证明最优的贡献一定是从下依次合并到上的 不会出现一个节点不能合并到父亲节点,却能合并到父亲节点的祖先节点的情况 我们设当前的节点为 \(u\),\(u\ ...

  2. Sticks(UVA - 307)【DFS+剪枝】

    Sticks(UVA - 307) 题目链接 算法 DFS+剪枝 1.这道题题意就是说原本有一些等长的木棍,后来把它们切割,切割成一个个最长为50单位长度的小木棍,现在想让你把它们组合成一个个等长的大 ...

  3. [学习笔记] Tarjan算法求强连通分量

    今天,我们要探讨的就是--Tarjan算法. Tarjan算法的主要作用便是求一张无向图中的强连通分量,并且用它缩点,把原本一个杂乱无章的有向图转化为一张DAG(有向无环图),以便解决之后的问题. 首 ...

  4. rxjs入门7之其它操作符复习

    一.辅助类操作符 二.过滤数据流 三.转化数据流 四.异常错误处理 五.多播 ,Subject类型

  5. Python+Appium自动化测试(7)-截图方法

    一,selenium模块的两种截图方法 get_screenshot_as_file(filename) 参数filename为截图文件保存的绝对路径,如: driver.get_screenshot ...

  6. centos7虚拟机时间和本地时间相差8小时

    安装ntp和ntpdate 在安装centos7虚拟机的时候,已经将时区设置为了Asia/shanghai,但还是出现时间不准,相差了8小时 可以安装ntp和ntpdate,使用 NTP 公共时间服务 ...

  7. Anno 框架 增加缓存、限流策略、事件总线、支持 thrift grpc 作为底层传输

    github 地址:https://github.com/duyanming/dymDemo dym 分布式开发框架 Demo 熔断 限流 事件总线(包括基于内存的.rabbitmq的) CQRS D ...

  8. swoft配置连接池

    bean.php 'db' => [ 'class' => Database::class, 'dsn' => 'mysql:dbname=test;host=127.0.0.1', ...

  9. 如何使用 Gin 和 Gorm 搭建一个简单的 API 服务 (二)

    创建 API   我们之前已经跑过 Gin 框架的代码,现在是时候加些功能进去了. 读取全部信息   我们先从"增删改查"中的"查"入手,查询我们之前添加的信息.我接下来要删除几行代码,并把 Gin ...

  10. nginx 是如何处理过期事件的?

    目录 什么是过期事件 nginx 是如何处理过期事件的? 参考资料 什么是过期事件 对于不需要加入到 post 队列 延后处理的事件,nginx 的事件都是通过 ngx_epoll_process_e ...