使用python3.6操作mysql
#coding:utf-8
#python3.6使用pymysql操作mysql
print("=====================mysql数据库=====================")
import pymysql.cursors
# 连接数据库
connect = pymysql.Connect(
host='127.0.0.1',
port=3306,
user='root',
passwd='19910101a',
db='note',
charset='utf8'
)
# 获取游标
cursor = connect.cursor()
#删除表
sql = 'DROP TABLE IF EXISTS student'
cursor.execute(sql)
connect.commit()
print('如果存在表就删除表格')
#创建表格
sql = "CREATE TABLE student(id INTEGER PRIMARY KEY,name TEXT)"
try:
cursor.execute(sql)
connect.commit()
except:
print("表已存在")
print('成功创建表格')
# 插入数据
sql = "INSERT INTO student VALUES(%d,'%s')"
data = (1, 'student1')
cursor.execute(sql % data)
connect.commit()
print('成功插入', cursor.rowcount, '条数据')
# 查询数据方法2,注意这种方式会自动帮你添加引号
sql = "INSERT INTO student VALUES(%s,%s)"
data = (1, 'student1')
cursor.execute(sql, data)
connect.commit()
print('成功插入', cursor.rowcount, '条数据')
# 修改数据
sql = "UPDATE student SET name = '%s' WHERE id = %d "
data = ('student2', 1)
cursor.execute(sql % data)
connect.commit()
print('成功修改', cursor.rowcount, '条数据')
# 查询数据
sql = "SELECT * FROM student WHERE id=%d"
data = (1,)
cursor.execute(sql % data)
for row in cursor.fetchall():
print("%s" % str(row))
print('共查找出', cursor.rowcount, '条数据')
# 删除数据
sql = "DELETE FROM student WHERE id = %d LIMIT %d"
data = (1, 1)
cursor.execute(sql % data)
connect.commit()
print('成功删除', cursor.rowcount, '条数据')
# 事务处理
sql_1 = "UPDATE student SET name = name + '1' WHERE id = 1 "
try:
cursor.execute(sql_1)
except Exception as e:
connect.rollback() # 事务回滚
print('事务处理失败', e)
else:
connect.commit() # 事务提交
print('事务处理成功', cursor.rowcount)
# 关闭连接
cursor.close()
connect.close()
#pymysql.Connect()参数说明
#host(str): MySQL服务器地址
#port(int): MySQL服务器端口号
#user(str): 用户名
#passwd(str): 密码
#db(str): 数据库名称
#charset(str): 连接编码
#
#connection对象支持的方法
#cursor() 使用该连接创建并返回游标
#commit() 提交当前事务
#rollback() 回滚当前事务
#close() 关闭连接
#
#cursor对象支持的方法
#execute(op) 执行一个数据库的查询命令
#fetchone() 取得结果集的下一行
#fetchmany(size) 获取结果集的下几行
#fetchall() 获取结果集中的所有行
#rowcount() 返回数据条数或影响行数
#close() 关闭游标对象
...全文
相关推荐
python3.6连接mysql数据库及增删改查操作详解
在本文中,我们将详细探讨如何使用 Python 3.6 连接到 MySQL 数据库并进行基本的 CRUD(创建、读取、更新、删除)操作。
Python3.6简单的操作Mysql数据库的三个实例
本篇文章主要介绍了如何使用Python 3.6与PyMySQL库来操作MySQL数据库的三个实例。首先,我们从安装PyMySQL模块开始,这是通过pip进行安装的,官方仓库链接为<https://gi
Python3.6简单操作Mysql数据库
下面我们将深入探讨如何使用Python3.6通过`pymysql`库进行MySQL数据库的简单操作。首先,要开始使用`pymysql`,你需要确保已经安装了这个库。
python 3.6 +pyMysql 操作mysql数据库(实例讲解)
在Python 3.6中,当你需要操作MySQL数据库时,pyMysql库是一个常用的选择。本文将通过实例讲解如何使用Python 3.6和pyMysql来连接并操作MySQL数据库。
Python3.6 使用pymysql库操作mysql,实现读写分离
本文介绍了如何通过代码实现用户登录功能,包括用户信息的增删改查操作。代码首先导入Load函数加载模块,然后使用Model类对数据库中的'user'表进行操作,如插入、删除和提交更改。最后通过输入用户名


其他技术讨论专区
