您的位置:首页 > 编程语言 > Python开发

Python进阶-连接 Mysql

2016-11-11 20:02 281 查看

Python

本篇文章主要用 PyMySQL 来实现Python3 Mysql数据的连接。

PyMySql 安装

$ git clone https://github.com/PyMySQL/PyMySQL

$ cd PyMySQL/

$ python3 setup.py install

安装过程如下图所示:



数据库连接

import pymysql
#打开数据库连接
db = pymysql.connect('localhost', 'username', 'password', 'testDB')
#使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
#使用 execute()  方法执行 SQL 查询
cursor.execute("SELECT VERSION()")
#使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
print("Database version : %s " % data) #输出结果:{Database version : 5.7.13} 说明数据库连接成功
db.close() # 关闭数据库连接


数据插入

已经在我的数据库下建立了 User 这张表,字段分别有id,name,age,以下实例使用 Sql 的 insert 语句向 User 表中插入一条数据。

#插入数据('jf',26)到表中
import pymysql
db = pymysql.connect('localhost', 'username', 'password', 'testDB')
cursor = db.cursor()
# SQL 插入语句
sql = """insert into User(name,age) VALUES ('jf',26)"""
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()


数据查询

Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。

- fetchone(): 该方法获取下一个查询结果集。结果集是一个对象。

- fetchall(): 接收全部的返回结果行。

- rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。

#查询 id=1的数据记录
import pymysql
db = pymysql.connect('localhost', ' username', 'password', 'testDB')
cursor = db.cursor()
sql = "select * from EMPLOYEE where id=1"
try:
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
id = row[0]
name=row[1]
age = row[2]
print("id=%d,name=%s,age=%d" % (id,name, age))
#id=1,name=jf,age=26
except:
print('Error,unable to fetch data')


数据更新

#id=1的年龄增加一岁
import pymysql
db = pymysql.connect('localhost', 'username', 'password', 'testDB')
cursor = db.cursor()
sql = "update USER set age=age+1 where id=1"
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()


数据删除

#年龄大于20岁的删除
import pymysql
db = pymysql.connect('localhost', 'username', 'password', 'testDB')
cursor = db.cursor()
sql = "delete from EMPLOYEE where age>20"
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
db.close()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python mysql 数据库