程序员对python数据库操作

python数据库操作 - PyMySQL入门

PyMySQL是Python中操作MySQL的模块,和之前使用的MySQLdb模块基本功能一致,PyMySQL的性能和MySQLdb几乎相当,如果对性能要求不是特别的强,使用PyMySQL将更加方便,PyMySQL是完全使用python编写,避免了MySQLdb跨系统分别安装的麻烦。

程序员对python数据库操作 - PyMySQL入门

适用环境

python版本 >=2.6或3.3

mysql版本>=4.1

安装

在命令行下执行命令:

pip install pymysql

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

python setup.py install

程序员对python数据库操作 - PyMySQL入门

建议使用pip安装, 可以自动解决包依赖问题,避免安装中出现各种错误。

pymysql的基本操作如下:

1#!/usr/bin/env python

2# --coding = utf-8

3# Author Allen Lee

4import pymysql

5#创建链接对象

6conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='Allen')

7#创建游标

8cursor = conn.cursor()

9#执行sql,更新单条数据,并返回受影响行数

10effect_row = cursor.execute("update hosts set host = '1.1.1.2'")

11#插入多条,并返回受影响的函数

12effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)",[("1.0.0.1",1,),("10.0.0.3",2)])

13#获取最新自增ID

14new_id = cursor.lastrowid

15#查询数据

16cursor.execute("select * from hosts")

17#获取一行

18row_1 = cursor.fetchone()

19#获取多(3)行

20row_2 = cursor.fetchmany(3)

21#获取所有

22row_3 = cursor.fetchall()

23#重设游标类型为字典类型

24cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

25#提交,保存新建或修改的数据

26conn.commit()

27#关闭游标

28cursor.close()

29#关闭连接

30conn.close()

程序员对python数据库操作 - PyMySQL入门

喜欢请关注


分享到:


相關文章: