5.15 pymysql 模塊

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,正確的語法:--後至少有一個任意字符mysql

現象 

最後那一個空格,在一條sql語句中若是遇到select *
from t1 where id > 3 -- and name='egon';則--以後的條件被註釋掉了

#一、sql注入之:用戶存在,繞過密碼
egon' -- 任意字符

#二、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'],))
相關文章
相關標籤/搜索