温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用python3.6怎么连接mysql数据库并实现增删改查操作

发布时间:2021-05-26 11:12:54 来源:亿速云 阅读:182 作者:Leah 栏目:开发技术

这期内容当中小编将会给大家带来有关使用python3.6怎么连接mysql数据库并实现增删改查操作,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

1.通过 pip 安装 pymysql

进入 cmd  输入  pip install pymysql  

回车等待安装完成;

使用python3.6怎么连接mysql数据库并实现增删改查操作

安装完成后出现如图相关信息,表示安装成功。

2.测试连接

import pymysql #导入 pymysql

如果编译未出错,即表示 pymysql 安装成功

简单的增删改查操作

示例表结构

使用python3.6怎么连接mysql数据库并实现增删改查操作

2.1查询操作i

import pymysql #导入 pymysql
 
#打开数据库连接
db= pymysql.connect(host="localhost",user="root",
 	password="123456",db="test",port=3307)
 
# 使用cursor()方法获取操作游标
cur = db.cursor()
 
#1.查询操作
# 编写sql 查询语句 user 对应我的表名
sql = "select * from user"
try:
	cur.execute(sql) 	#执行sql语句
 
	results = cur.fetchall()	#获取查询的所有记录
	print("id","name","password")
	#遍历结果
	for row in results :
		id = row[0]
		name = row[1]
		password = row[2]
		print(id,name,password)
except Exception as e:
	raise e
finally:

2.2插入操作

import pymysql
#2.插入操作
db= pymysql.connect(host="localhost",user="root",
 	password="123456",db="test",port=3307)
 
# 使用cursor()方法获取操作游标
cur = db.cursor()
 
sql_insert ="""insert into user(id,username,password) values(4,'liu','1234')"""
 
try:
	cur.execute(sql_insert)
	#提交
	db.commit()
except Exception as e:
	#错误回滚
	db.rollback() 
finally:
	db.close()

2.3更新操作

import pymysql
#3.更新操作
db= pymysql.connect(host="localhost",user="root",
 	password="123456",db="test",port=3307)
 
# 使用cursor()方法获取操作游标
cur = db.cursor()
 
sql_update ="update user set username = '%s' where id = %d"
 
try:
	cur.execute(sql_update % ("xiongda",3)) #像sql语句传递参数
	#提交
	db.commit()
except Exception as e:
	#错误回滚
	db.rollback() 
finally:
	db.close()

2.4删除操作

import pymysql
#4.删除操作
db= pymysql.connect(host="localhost",user="root",
 	password="123456",db="test",port=3307)
 
# 使用cursor()方法获取操作游标
cur = db.cursor()
 
sql_delete ="delete from user where id = %d"
 
try:
	cur.execute(sql_delete % (3)) #像sql语句传递参数
	#提交
	db.commit()
except Exception as e:
	#错误回滚
	db.rollback() 
finally:
	db.close()

Python主要用来做什么

Python主要应用于:1、Web开发;2、数据科学研究;3、网络爬虫;4、嵌入式应用开发;5、游戏开发;6、桌面应用开发。

上述就是小编为大家分享的使用python3.6怎么连接mysql数据库并实现增删改查操作了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI