python3操作mysql数据库的方法
作者:python客栈 时间:2023-07-28 15:48:27
软硬件环境
OS X EI Capitan
Python 3.5.1
mysql 5.6
前言
在开发中经常涉及到数据库的使用,而python对于数据库也有多种解决方法。本文以python3中的mysql为例,介绍pymysql模块的使用。
准备数据库
创建一个mysql数据库,名字叫testdb,建立一张表叫testtable,它有3个字段,分别是id,数据类型是INT(11),设为主键、非空、UNSIGNED、AUTO INCREMENT,name,数据类型是VARCHAR(45),设为非空、唯一,sex,数据类型是VARCHAR(45),设为非空
python3 源码
# -*- coding: utf-8 -*-
__author__ = 'djstava@gmail.com'
import logging
import pymysql
class MySQLCommand(object):
def __init__(self,host,port,user,passwd,db,table):
self.host = host
self.port = port
self.user = user
self.password = passwd
self.db = db
self.table = table
def connectMysql(self):
try:
self.conn = pymysql.connect(host=self.host,port=self.port,user=self.user,passwd=self.password,db=self.db,charset='utf8')
self.cursor = self.conn.cursor()
except:
print('connect mysql error.')
def queryMysql(self):
sql = "SELECT * FROM " + self.table
try:
self.cursor.execute(sql)
row = self.cursor.fetchone()
print(row)
except:
print(sql + ' execute failed.')
def insertMysql(self,id,name,sex):
sql = "INSERT INTO " + self.table + " VALUES(" + id + "," + "'" + name + "'," + "'" + sex + "')"
try:
self.cursor.execute(sql)
except:
print("insert failed.")
def updateMysqlSN(self,name,sex):
sql = "UPDATE " + self.table + " SET sex='" + sex + "'" + " WHERE name='" + name + "'"
print("update sn:" + sql)
try:
self.cursor.execute(sql)
self.conn.commit()
except:
self.conn.rollback()
def closeMysql(self):
self.cursor.close()
self.conn.close()
标签:python3,mysql
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
在pycharm中使用pipenv创建虚拟环境和安装django的详细教程
2021-06-06 19:02:37
![](https://img.aspxhome.com/file/2023/9/102999_0s.png)
python获取网页中所有图片并筛选指定分辨率的方法
2021-07-28 04:57:23
![](https://img.aspxhome.com/file/2023/6/71446_0s.jpg)
Python实现查找二叉搜索树第k大的节点功能示例
2023-12-17 04:40:09
![](https://img.aspxhome.com/file/2023/4/101584_0s.png)
在django项目中,如何单独运行某个python文件
2023-04-27 07:37:22
Python数组定义方法
2021-05-30 08:46:39
python中的文件打开与关闭操作命令介绍
2021-07-05 10:15:39
MySQL日期数据类型、时间类型使用总结
2024-01-27 09:46:51
python模拟点击在ios中实现的实例讲解
2021-11-28 13:03:34
vue 解决data中定义图片相对路径页面不显示的问题
2024-04-30 10:24:52
![](https://img.aspxhome.com/file/2023/9/130219_0s.jpg)
MySQL优化全攻略--相关数据库命令
2008-11-01 17:03:00
javascript闭包的秘密
2008-09-28 20:39:00
python的random和time模块详解
2023-07-27 18:16:27
![](https://img.aspxhome.com/file/2023/5/61215_0s.png)
vue如何使用rem适配
2024-04-30 08:44:49
![](https://img.aspxhome.com/file/2023/5/132995_0s.png)
python3爬虫之设计签名小程序
2021-09-16 00:26:46
![](https://img.aspxhome.com/file/2023/7/113167_0s.png)
numpy.transpose对三维数组的转置方法
2023-10-11 07:32:36
设计的俗化特征
2010-04-08 16:07:00
![](https://img.aspxhome.com/file/UploadPic/20104/8/01-49s.jpg)
GO 反射对性能的影响分析
2024-02-18 06:51:41
js 数值项目的格式化函数代码
2023-07-14 16:51:31
Python的这些库,你知道多少?
2021-12-12 04:02:39
![](https://img.aspxhome.com/file/2023/2/103772_0s.png)
python解析xml文件方式(解析、更新、写入)
2022-03-07 05:19:01
![](https://img.aspxhome.com/file/2023/3/68853_0s.jpg)