https://pypi.python.org/pypi
相当于python 的应用市场
pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb几乎相同。
下载安装
使用操作
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 26 | #!/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 () # 执行SQL,并返回收影响行数 effect_row = cursor . execute ( "update hosts set host = '1.1.1.2'" ) # 执行SQL,并返回受影响行数 #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 () |
严禁用左边的方法,必须使用参数形式,避免sql注入问题
effect_row =
cursor
.
execute
(
"update hosts set host = '1.1.1.2' where nid > %s"
, (1,))
给execute()传两个参数,会自动替换%s实现动态拼接,且%s不用带引号
取第一条
取3条,3可改
SQL注入:
拿到最新一条数据的自增ID