Python进阶-连接 Mysql

来源:互联网 发布:newsql数据库有哪些 编辑:程序博客网 时间:2024/06/06 12:51

Python

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

PyMySql 安装

  1. $ git clone https://github.com/PyMySQL/PyMySQL
  2. $ cd PyMySQL/
  3. $ python3 setup.py install
    安装过程如下图所示:
    git 命令安装 PyMySql

数据库连接

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
原创粉丝点击