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. 推荐一款IDEA神器!一键查看Java字节码以及其他类信息

    由于后面要分享的一篇文章中用到了这篇文章要推荐的一个插件,所以这里分享一下.非常实用!你会爱上它的! 开始推荐 IDEA 字节码查看神器之前,先来回顾一下 Java 字节码是啥. 何为 Java 字节 ...

  2. 【贪心算法】CF Emergency Evacuation

    题目大意 vjudge链接 给你一个车厢和一些人,这些人都坐在座位上,求这些人全部出去的时间最小值. 样例1输入 5 2 71 11 21 32 32 44 45 2 样例1输出 9 样例2输入 50 ...

  3. 自定义常用input表单元素二:纯css实现自定义radio单选按钮

    这是接着上一篇纯css自定义复选框checkbox的第二篇,自定义一个radio单选按钮,同样,采用css伪类和"+"css选择器为思路,下面是预览图: 下面直入主题放代码:HTM ...

  4. Redis6 安装

    在centos7.5服务器上按照官方发布的安装方式并不能进行正确的安装,现收集并整理如下安装方式,亲测有效 1.安装依赖 yum install -y cpp binutils glibc glibc ...

  5. selenium-窗口切换

    方法一 # 获取打开的多个窗口句柄 windows = driver.window_handles # 切换到当前最新打开的窗口 driver.switch_to.window(windows[-1] ...

  6. phpstorm 使用xdebug

    一.在phpstudy配置 开启xdebug的zend扩展,在php.ini 中添加下面的代码: [xdebug] zend_extension = "D:\phpstudy_pro\Ext ...

  7. salesforce零基础学习(九十六)项目中的零碎知识点小总结(四)

    本篇参考: https://developer.salesforce.com/docs/atlas.en-us.216.0.apexcode.meta/apexcode/apex_classes_ke ...

  8. 使用PL/SQL Developer 学习pl/sql

    1.创建表并且插入一些数据 (这里表名为test): 2. New 一个SQL Window敲下如下代码(--为注释部分): declare   --declare:用于plsql中的声明变量,和be ...

  9. Stream(一)

    public class Test06 { /* * StreamAPI: * StreamAPI是用来处理数据,处理集合等容器中的数据,处理操作有:查询.筛选.删除.过滤.统计.映射等. * 希望能 ...

  10. Qlik Sense插件及QRS接口补充

    date: 2019-10-18 09:10:00 updated: 2019-10-18 15:18:00 Qlik Sense插件及QRS接口补充 1.插件 1.1 获取数据方式 理论上 Engi ...