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()
相关文章推荐
- python3连接mysql 稍微进阶 + 日期处理
- python连接mysql-mysqldb
- Python连接MySQL的实例代码
- Python与MySQL连接
- web测试常用python代码——mysql连接以及语句执行
- python连接mysql查询数据返回字典格式
- python 连接mysql
- python连接MySQL
- python中使用MySQLdb连接mysql
- linux下python 连接mysql
- python连接mysql报错
- Python连接MySQL的实例代码
- 关于MySQLdb的一些新发现(使用python连接mysql的库)
- python 26 连接 mysql 实例
- python 连接mysql
- 安装MySQL-python(MySQLdb)时报错,找不到libmysqlclient_r.so.16动态连接库
- 编译了windows下的python3连接Mysql的库mypysql
- python3 用ceODBC 在windows下连接mysql
- Python2.6 连接MySQL环境搭建测试
- Python 连接MySQL 简介