pymysql 模块
安装
pip3 install pymysql
链接,执行sql,关闭(游标)
import pymysql user= input('用户名:>>').strip() pwd= input('密码:>>').strip() # 先链接,拿到游标 conn=pymysql.connect(host='localhost',user='root',password='123456', database='day47',charset='utf8') cursor=conn.cursor() # 拿到游标,即mysql > # 执行sql sql='select * from user where user="%s" and password="%s";'%(user,pwd) print(sql) # 注意%s需要加双引号 rows = cursor.execute(sql) # 拿到受影响的行数 cursor.close() conn.close() if rows: print('登录成功') else: print('登录失败')
execute()之sql注入
原理
符号--会注释掉它之后的sql,正确的语法:--后至少有一个任意字符
现象
最后那一个空格,在一条sql语句中如果遇到select * from t1 where id > 3 -- and name='egon';则--之后的条件被注释掉了 #1、sql注入之:用户存在,绕过密码 egon' -- 任意字符 #2、sql注入之:用户不存在,绕过用户与密码 xxx' or 1=1 -- 任意字符
解决方式
# 原来是我们对sql进行字符串拼接 # sql="select * from userinfo where name='%s' and password='%s'" %(user,pwd) # print(sql) # rows=cursor.execute(sql) #改写为(execute帮我们做字符串拼接,我们无需且一定不能再为%s加引号了) sql="select * from userinfo where name=%s and password=%s" # 注意%s需要去掉引号,因为pymysql会自动为我们加上 rows=cursor.execute(sql,[user,pwd]) #pymysql模块自动帮我们解决sql注入的问题,只要我们按照pymysql的规矩来。
增、批量增、删、改:conn.commit()
增
import pymysql 先链接,拿到游标 conn=pymysql.connect(host='localhost',user='root',password='123456',database='day47') cursor=conn.cursor() #拿到游标,即mysql > #执行sql 增: sql='insert into user1(user,password) VALUES (%s,%s)' print(sql) # rows = cursor.execute(sql,('xixi',123)) #插入一条记录 rows = cursor.executemany(sql,[('xixi',123),('aaa',456),('ttt',147)]) #插入多行记录 print('%s row in set (0.00 sec)'%rows) conn.commit() #提交到数据库 cursor.close() conn.close()
批量增加
# coding:utf-8 import pymysql # 打开数据库连接 db = pymysql.connect(host='localhost', port=3306, user='username', passwd='password', db='database_name', charset='utf8') # 使用cursor()方法获取操作游标 cursor = db.cursor() # SQL 插入语句 sql = "INSERT INTO EMPLOYEE(FIRST_NAME, AGE, SEX) VALUES (%s,%s,%s)" # 一个tuple或者list T = (('xiaoming', 31, 'boy'), ('hong', 22, 'girl'), ('wang', 90, 'man')) try: # 执行sql语句 cursor.executemany(sql, T) # 提交到数据库执行 db.commit() except : # 如果发生错误则回滚 db.rollback() # 关闭游标 cursor.close() # 关闭数据库连接 db.close()
删
import pymysql #先链接,拿到游标 name=input('>>').strip() conn=pymysql.connect(host='localhost',user='root',password='123456',database='day47') cursor=conn.cursor() #拿到游标,即mysql > #执行sql 删: sql='delete from user1 where user =%s;' #删除数据 print(sql) rows = cursor.execute(sql,(name)) print('%s row in set (0.00 sec)'%rows) conn.commit() #提交到数据库 cursor.close() conn.close()
改
import pymysql #先链接,拿到游标 id=input('>>').strip() conn=pymysql.connect(host='localhost',user='root',password='123456',database='day47') cursor=conn.cursor() #拿到游标,即mysql > #执行sql 改: sql=' update user1 set password = "5555555" where id=%s;' print(sql) rows = cursor.execute(sql,(id)) print('%s row in set (0.00 sec)'%rows) conn.commit() #提交到数据库 cursor.close() conn.close()
查:fetchone,fetchmany,fetchall
# ---------查fetchone,fetchmany,fetchall----------- import pymysql conn=pymysql.connect(host='localhost',user='root',password='123456',database='day47') cursor=conn.cursor() #拿到游标,即mysql > #执行sql 查: sql='select * from user1;' rows = cursor.execute(sql) #查单条fetchone res1=cursor.fetchone() res2=cursor.fetchone() res3=cursor.fetchone() print(res1) print(res2) print(res3) print(res3[0]) #查多条fetchmany print(cursor.fetchmany(3)) print(cursor.fetchone()) #查所有fetchall print(cursor.fetchall()) print(cursor.fetchone()) #-------光标的移动-------- #1.绝对路径:从文件的开头位置算起 print(cursor.fetchall()) cursor.scroll(1,mode='absolute') print(cursor.fetchone()) cursor.scroll(3,mode='absolute') print(cursor.fetchone()) #2.相对路径: print(cursor.fetchone()) print(cursor.fetchone()) cursor.scroll(2,mode='relative') #相对于上面的两条向后移两条 print(cursor.fetchone()) print('%s row in set (0.00 sec)' %rows) cursor.close() conn.close()
获取插入的最后一条数据的自增ID
------查看表中最后一行的iD import pymysql conn=pymysql.connect(host='localhost',user='root',password='123456', database='day47',charset='utf8') cursor=conn.cursor() sql='insert into user1(user,password) values(%s,%s);' rows=cursor.execute(sql,('alex','123')) # rows=cursor.executemany(sql,[('yuanhao','123'),('laowu','123'),('kgf','12323')]) conn.commit() print(cursor.lastrowid) #查看表中最后一行的iD cursor.close() conn.close()
异步处理
# 用twisted库将数据进行异步插入到数据库 import pymysql from twisted.enterprise import adbapi from twisted.internet import reactor class MysqlTwistedPipeline(object): def __init__(self, dbpool): self.dbpool = dbpool @classmethod def from_settings(cls, settings): # 需要在setting中设置数据库配置参数 dbparms = dict( host=settings['MYSQL_HOST'], db=settings['MYSQL_DBNAME'], user=settings['MYSQL_USER'], passwd=settings['MYSQL_PASSWORD'], charset='utf8', cursorclass=pymysql.cursors.DictCursor, use_unicode=True, ) # 连接ConnectionPool(使用MySQLdb连接,或者pymysql) dbpool = adbapi.ConnectionPool("MySQLdb", **dbparms) # **让参数变成可变化参数 return cls(dbpool) # 返回实例化对象 def process_item(self, item, spider): # 使用twisted将MySQL插入变成异步执行 query = self.dbpool.runInteraction(self.do_insert, item) # 添加异常处理 query.addCallback(self.handle_error) def handle_error(self, failure): # 处理异步插入时的异常 print(failure) def do_insert(self, cursor, item): # 执行具体的插入 insert_sql = """ insert into jobbole_artitle(name, base_url, date, comment) VALUES (%s, %s, %s, %s) """ cursor.execute(insert_sql, (item['name'], item['base_url'], item['date'], item['coment'],))