链条传动

砥砺前行,不忘初心!

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
"""
http://www.cnblogs.com/wupeiqi/articles/5699254.html

安装:pip3 install pymysql
"""
import pymysql

# 连接数据库。参数:主机、端口、用户名、密码、数据库名称
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='pytestdb')

# 创建游标,用游标来操作数据库
# cursor = conn.cursor()   # 默认取值时是以元组形式来取
cursor = conn.cursor(pymysql.cursors.DictCursor)  # 加参数后取值以字典形式来取

"""
# 执行SQL,返回受影响函数
effect_row = cursor.execute("update host set host='192.168.1.22'")
print(effect_row)

# 执行SQL,并返回受影响行数(动态参数)
# effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,))

# 执行SQL,并返回受影响行数(同时执行多条SQL语句)
# effect_row = cursor.executemany("insert into hosts(host,color_id) values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])
"""

# 查询并取查询的数据
# 执行SQL语句
effect_row = cursor.execute("select * from host")

# row_1 = cursor.fetchone()  # 获取查询的第一条数据------一条一条取数据,如果接下来再执行cursor.fetchone(),就会获得下一条数据
# row_2 = cursor.fetchmany(2)   # 获取查询的前2条数据---2条2条取数据,如果接下来再执行cursor.fetchmany(2),就会获得下2条数据
row_3 = cursor.fetchall()    # 获取查询的所有数据(每条数据都是一个元组)
print(row_3)

# 注:在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:
# cursor.scroll(1,mode='relative')  # 相对当前位置向下移动一个位置
# cursor.scroll(2,mode='absolute') # 相对绝对位置移动(移动到所有数据的第2个位置)


# 将修改提交到数据库
conn.commit()

# 关闭游标
cursor.close()

# 关闭数据库连接
conn.close()

# print(cursor.lastrowid)   # 插入数据时,获取最后一条插入数据的自增id

 

posted on 2016-12-02 14:48  链条君  阅读(141)  评论(0编辑  收藏  举报