Python进阶-连接 Mysql
来源:互联网 发布:newsql数据库有哪些 编辑:程序博客网 时间:2024/06/06 12:51
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() 方法创建一个游标对象 cursorcursor = 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 pymysqldb = 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 pymysqldb = 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=26except: print('Error,unable to fetch data')
数据更新
#id=1的年龄增加一岁import pymysqldb = 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 pymysqldb = 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()
0 0
- Python进阶-连接 Mysql
- Python进阶(五十二)-Flask使用pymysql连接MySQL数据库
- 【进阶】MySQL中的连接查询
- Python进阶(二十三)-Django使用pymysql连接MySQL数据库做增删改查
- Python连接Mysql 连接池
- python连接mysql数据库
- Python连接MySQL
- python连接mysql数据库
- python连接mysql
- python 连接mysql
- python连接MySQL数据库
- Python连接mysql数据库
- Python连接mysql
- python 连接mysql
- python连接mysql
- Python连接MYSQL --- MySQLdb
- python连接mysql数据库
- python连接mysql
- php与前端(三):下拉框搜索 select2 的使用
- Android 项目中添加一个新类,无法在其它类中使用
- c++ 数据结构 双向循环链表
- Javascript 高级 ajax 、jsonp
- openjudge动规刷题攻略----第一弹
- Python进阶-连接 Mysql
- Find The Multiple poj1426 (DFS)
- Spark-RDD编程基础
- weka连接mysql
- java : Iterator Pattern
- Android创建原图的副本
- 非root下,如何将android中的数据库文件存放到外部存储并导出
- 学习classList写的小Demo
- hdu4292——Food(SAP+拆点)