当前位置:天才代写 > tutorial > Python教程 > python数据库操纵 – PyMySQL入门

python数据库操纵 – PyMySQL入门

2017-11-02 08:00 星期四 所属: Python教程 浏览:534

PyMySQL是Python中操纵MySQL的模块,和之前利用的MySQLdb模块根基成果一致,PyMySQL的机能和MySQLdb险些相当,假如对机能要求

不是出格的强,利用PyMySQL将越发利便,PyMySQL是完全利用python编写,制止了MySQLdb跨系统别离安装的贫苦。

合用情况

python版本 >=2.6或3.3

mysql版本>=4.1

安装

在呼吁行下执行呼吁:

pip install pymysql

手动安装,请先下载。下载地点:https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X。

个中的X.X是版本。

下载后解压压缩包。在呼吁行中进入解压后的目次,执行如下的指令:

python setup.py install

发起利用pip安装, 可以自动办理包依赖问题,制止安装中呈现各类错误。

pymysql的根基操纵如下:

#!/usr/bin/env python
#   --coding = utf-8
#   Author Allen Lee
import pymysql
#建设链接工具
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='Allen')
#建设游标
cursor = conn.cursor()
#执行sql,更新单条数据,并返回受影响行数
effect_row = cursor.execute("update hosts set host = '1.1.1.2'")
#插入多条,并返回受影响的函数
effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)",[("1.0.0.1",1,),("10.0.0.3",2)])
#获取最新自增ID
new_id = cursor.lastrowid
#查询数据
cursor.execute("select * from hosts")
#获取一行
row_1 = cursor.fetchone()
#获取多(3)行
row_2 = cursor.fetchmany(3)
#获取所有
row_3 = cursor.fetchall()
#重设游标范例为字典范例
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
#提交,生存新建或修改的数据
conn.commit()
#封锁游标
cursor.close()
#封锁毗连
conn.close()

 

    关键字:

天才代写-代写联系方式