使用PyMySQL连接Mysql---(python3.6&mysql5.7)
环境:
python: Python 3.6.5 #安装在win7系统
mysql: 5.7.21 #安装在Linux-CentOS6.8系统
1、通过pip安装pymysql:
进入python根目录Scrips目录下
安装命令:pip install PyMySQL
如上图所示安装完成。
2、创建连接mysql文件
在C:\meng\python目录下创建文件名称为mysql_test.py文件,文件内容如下:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import pymysql
# 打开数据库连接(ip/数据库用户名/登录密码/数据库名/编码)
db = pymysql.connect("192.168.1.121", "root", "root", "mtest", charset='utf8' )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取一条数据
data = cursor.fetchone()
print ("Database version : %s " % data)
# 关闭数据库连接
db.close()
简单测试一下,打开doc窗口,定位到C:\meng\python这个目录,使用一下的命令执行py文件:
C:\meng\python>py mysql_test.py
Database version :
5.7.21-log
由此可见,查到了mysql的版本,连接成功!!!
二、Python操作MySql数据库实现增删改查
1、数据库查询
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import pymysql
# 打开数据库连接(ip/数据库用户名/登录密码/数据库名)
db = pymysql.connect("192.168.1.121","root","root","mtest",charset='utf8')
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# SQL 查询语句
sql = "SELECT * FROM mt3"
try:
# 执行SQL语句
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
id = row[0]
name = row[1]
phone = row[2]
# 打印结果
print("id=%d,name=%s,phone=%d" % (id,name,phone))
except:
print("Error: unable to fecth data")
# 关闭数据库连接
db.close()
#end
注:说明id是int类型,name是varchar类型,phone是int类型;
2、数据库插入操作
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import pymysql
# 打开数据库连接(ip/数据库用户名/登录密码/数据库名)
db = pymysql.connect("192.168.1.121","root","root","mtest",charset='utf8')
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# SQL 插入语句
sql = "INSERT INTO mt3(name,phone) VALUES ('Zhangm',111222)"
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# 如果发生错误则回滚
db.rollback()
# 关闭数据库连接
db.close()
#end
3、更新数据库
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import pymysql
# 打开数据库连接(ip/数据库用户名/登录密码/数据库名)
db = pymysql.connect("192.168.1.121","root","root","mtest",charset='utf8')
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# SQL 插入语句
sql = "update mt3 set name='Liusan1111' where id = 4 "
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# 如果发生错误则回滚
db.rollback()
# 关闭数据库连接
db.close()
#end
4、删除数据
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import pymysql
# 打开数据库连接(ip/数据库用户名/登录密码/数据库名)
db = pymysql.connect("192.168.1.121","root","root","mtest",charset='utf8')
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# SQL 插入语句
sql = "delete from mt3 where id = 4"
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# 如果发生错误则回滚
db.rollback()
# 关闭数据库连接
db.close()
#end