python3.6使用pymysql连接Mysql数据库

yipeiwu_com5年前Python基础

python3.6使用pymysql连接Mysql数据库及简单的增删改查操作,供大家参考,具体内容如下

折腾好半天的数据库连接,由于之前未安装pip ,而且自己用的Python 版本为3.6. 只能用 pymysql 来连接数据库,(如果有和我一样未安装 pip 的朋友请 点这里windows下python安装pip简易教程),下边简单介绍一下连接的过程,以及简单的增删改查操作。

1.通过pip 安装pymysql

进入 cmd  输入  pip install pymysql 
回车等待安装完成;

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

2.测试连接

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

简单的增删改查操作

示例表结构

2.1查询操作

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: 
 db.close() #关闭连接 

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 SSH模块登录,远程机执行shell命令实例解析

用python SSH模块登录,并在远程机执行shell命令 (在CentOS 7 环境试验成功, Redhat 系列应该是兼容的。) 先安装必须的模块 # yum install...

matplotlib实现区域颜色填充

matplotlib实现区域颜色填充

本文实例为大家分享了matplotlib实现区域颜色填充的具体代码,供大家参考,具体内容如下 import matplotlib.pyplot as plt import nump...

Scrapy框架使用的基本知识

scrapy是一个基于Twisted的异步处理框架,可扩展性很强。优点此处不再一一赘述。 下面介绍一些概念性知识,帮助大家理解scrapy。 一、数据流向 要想熟练掌握这个框架,一定要明...

Python中应该使用%还是format来格式化字符串

%还是format 1、皇城PK Python中格式化字符串目前有两种阵营:%和format,我们应该选择哪种呢? 自从Python2.6引入了format这个格式化字符串的方法之后,我...

使用python turtle画高达

使用python turtle画高达

我就废话不多说了,直接上代码吧! import turtle t=turtle.Turtle() turtle.Turtle().screen.delay(0) tleft=turt...