1 #!/usr/bin/env python
2 #-*- coding:utf-8 _*-
3 """
4 @author:sujunjun
5 @file: 1.py
6 @time: 2017/12/09
7 """
8 import pymysql
9
10 # 创建连接
11 conn = pymysql.connect( host = '127.0.0.1', port = 3306, user = 'root', passwd = '123456', db = 'py' ,charset = 'utf8')
12 # 创建游标
13 #cursor = conn.cursor()
14 # 游标设置为字典类型
15 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
16
17 #更新
18 # 执行SQL,并返回收影响行数
19 #effect_row = cursor.execute( "update student set sname = %s where sid = %s",('小军',1,) ) #修改成功返回1修改失败返回0
20
21
22 #插入
23 # 执行SQL,并返回受影响行数
24 #effect_row = cursor.executemany("insert into student(gender,class_id,sname)values(%s,%s,%s)", [("男",4,'张晓军'),("女",4,'小花')]) #插入多条
25 #effect_row = cursor.execute("insert into student(gender,class_id,sname)values(%s,%s,%s)", ("女",4,'战天狗')) #插入一条
26 # 获取最新自增ID
27 #new_id = cursor.lastrowid #如果是插入多条获取的是最后插入的那个id
28 #conn.commit()
29
30 #删除
31 #effect_row = cursor.execute("delete from student where sid = %s",(19,))
32
33 #查询
34 cursor.execute( "select * from student" )
35
36 # 获取第一行数据 (常用)
37 #row_1 = cursor.fetchone()#(1, '男', 1, '小军') 指针会下移
38 #row_1 = cursor.fetchone() #(3, '男', 1, '张三')
39 #row_1 = cursor.fetchone() #(3, '男', 1, '张三')
40
41 # 获取前n行数据
42 #row_2 = cursor.fetchmany(2) #这个不常用
43
44
45 # 获取所有数据(常用)
46 row_3 = cursor.fetchall() #获取所有数据 默认以元组方式返回
47
48
49 print(row_3)
50
51
52 #注:在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:
53 #row_1 = cursor.fetchone()#(1, '男', 1, '小军') 指针会下移
54 #row_1 = cursor.fetchone()#(2, '女', 1, '钢蛋') 指针会下移
55 #cursor.scroll(11,mode='absolute') # 绝对位置移动 指定移动多少位 从0开始,0是第一位
56 #cursor.scroll(-2,mode='relative') # 相对当前位置移动 #正数向下移动,负数向上移动 从0开始,0是第一位 写1的话相当于相对当前位置向下移动2位
57 # row_1 = cursor.fetchone()#
58 #print(row_1)
59
60 # 提交,不然无法保存新建或者修改的数据
61
62 a = 123 if 1!=1 else 456 #三元运算
63 print(a)
64 # 关闭游标
65 cursor.close()
66 # 关闭连接
67 conn.close()