1. 执行SQL
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | #!/usr/bin/env python # -*- coding:utf-8 -*- import pymysql # 创建连接 conn = pymysql.connect(host = '127.0.0.1' , port = 3306 , user = 'root' , passwd = '123' , db = 't1' ) # 创建游标 cursor = conn.cursor() # 执行update,并返回收影响行数, print(effect_row)返回受影响的行数 effect_row = cursor.execute( "update hosts set host = '1.1.1.2'" ) # 执行update,后面括号内容就是插入变量,%s,%d使用方式一样 #effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,)) # 执行SQL,并返回受影响行数 #effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)]) # 提交,不然无法保存新建或者修改的数据 conn.commit() # 关闭游标 cursor.close() # 关闭连接 conn.close() |
2、获取新创建数据自增ID
1 2 3 4 5 6 7 8 9 10 11 12 13 | #!/usr/bin/env python # -*- coding:utf-8 -*- import pymysql conn = pymysql.connect(host = '127.0.0.1' , port = 3306 , user = 'root' , passwd = '123' , db = 't1' ) cursor = conn.cursor() cursor.executemany( "insert into hosts(host,color_id)values(%s,%s)" , [( "1.1.1.11" , 1 ),( "1.1.1.11" , 2 )]) conn.commit() cursor.close() conn.close() # 获取最新自增ID new_id = cursor.lastrowid |
3、获取查询数据,使用fetch来获取查询的结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | #!/usr/bin/env python # -*- coding:utf-8 -*- import pymysql conn = pymysql.connect(host = '127.0.0.1' , port = 3306 , user = 'root' , passwd = '123' , db = 't1' ) cursor = conn.cursor() cursor.execute( "select * from hosts" ) # 获取第一行数据 row_1 = cursor.fetchone() # 获取前n行数据 # row_2 = cursor.fetchmany(3) # 获取所有数据 # row_3 = cursor.fetchall() conn.commit() cursor.close() conn.close() |
注:在fetch数据时按照顺序进行,可以使用cursor.scroll(num,mode)来移动游标位置,如:
- cursor.scroll(1,mode='relative') # 相对当前位置移动
- cursor.scroll(2,mode='absolute') # 相对绝对位置移动
4、fetch数据类型
关于默认获取的数据是元祖类型,如果想要或者字典类型的数据,即:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #!/usr/bin/env python # -*- coding:utf-8 -*- import pymysql conn = pymysql.connect(host = '127.0.0.1' , port = 3306 , user = 'root' , passwd = '123' , db = 't1' ) # 游标设置为字典类型 cursor = conn.cursor(cursor = pymysql.cursors.DictCursor) r = cursor.execute( "call p1()" ) result = cursor.fetchone() conn.commit() cursor.close() conn.close() |
fetchone只选择一个执行,如果执行两次fetchone会获取下一个结果,好像迭代器一样
fetchmany选择多个执行,fechmany(3)一次拿三次
fetchall选择全部执行
cursor.scroll(-1, mode='relative') # 相对的位置向上移动游标
cursor.scroll(2, mode='absolute') # 绝对的位置向下移动游标
MySQL 其他注意事项:
1. syntax = NULL 这是错误的写法,正确应该为 IS NULL,作为判断
2. inter join vs outer join
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步