python pymysql模塊

新建表mysql

import pymysql
conn=pymysql.connect(host='192.168.10.128',port=3306,user='root',passwd='123456',db='t-1',charset='utf8') #建立鏈接
cursor=conn.cursor() #建立遊標
effect_row=cursor.execute('create table t1(nid int(3),name VARCHAR(10),age int(4))')
print(effect_row)  #受影響的行數
conn.commit()     #提交
conn.close()

sql

#insert   嚴禁拼接會引發sql注入,錯誤方法(利用or 或-- 註釋)
nid=input("請輸入nid:")
name=input("請輸入name:")
age=input("請輸入age:")
sql="insert into t1(nid,name,age) value(%s,'%s',%s)" %(nid,name,age)
conn=pymysql.connect(host='192.168.10.128',port=3306,user='root',passwd='123456',db='t-1',charset='utf8')
cursor=conn.cursor()
effect_row=cursor.execute(sql)
conn.commit()
conn.close()

#正確方法
nid=input("請輸入nid:")
name=input("請輸入name:")
age=input("請輸入age:")
conn=pymysql.connect(host='192.168.10.128',port=3306,user='root',passwd='123456',db='t-1',charset='utf8')
cursor=conn.cursor()
effect_row=cursor.execute("insert into t1(nid,name,age) value(%s,%s,%s)",(nid,name,age))
inp_list=[
    (44,'huang',32),
    (45,'guan',38),
    (46,'guang',31)
]
effect_row1=cursor.executemany("insert into t1(nid,name,age) value(%s,%s,%s)",inp_list)  #多個插入,代碼內部作了個循環
conn.commit()
conn.close()
獲取最新自增ID
new_id =  cursor .lastrowid

fetch

#
conn=pymysql.connect(host='192.168.10.128',user='root',passwd='123456',db='t-1',charset='utf8')
cursor=conn.cursor()
effect_row=cursor.execute("delete from t1 where name='guang'")
conn.commit()
conn.close()

spa

#
conn=pymysql.connect(host='192.168.10.128',user='root',passwd='123456',db='t-1',charset='utf8')
cursor=conn.cursor()
effect_row=cursor.execute("update t1 set age=133 where name='as'")
conn.commit()
conn.close()

查 #無需commit指針

import pymysql
conn=pymysql.connect(host='192.168.10.128',user='root',passwd='123456',db='t-1',charset='utf8')
cusor=conn.cursor()
#cursor=conn.cursor(cursor=pymysql.cursors.DictCursor)  #以字典形式展現結果
effect_row=cursor.execute('select * from t1')
rowall=cursor.fetchall()   #獲取全部
cursor.scroll(0,mode='absolute')  #以絕對方式移動指針
row1_3=cursor.fetchmany(3)  #獲取前三行
cursor.scroll(-1,mode='relative') #以相對方式向前移動指針 +1向後移動指針
rowone=cursor.fetchone()    #獲取第一行
print (rowall)
print (row1_3)
print(rowone)
conn.close()

 

 sql注入演示code

import pymysql
nid="'任意輸入' or 1=1--"
age=32
sql="select * from t1 where nid=%s and age=%s" %(nid,age)
#這裏變成了 select * from t1 where nid='任意輸入' or 1=1-- and age=32 
conn=pymysql.connect(host='192.168.10.128',port=3306,user='root',passwd='123456',db='t-1',charset='utf8')
cursor=conn.cursor()
effect_row=cursor.execute(sql)
rowall=cursor.fetchall()
print(rowall)
conn.close()

相關文章
相關標籤/搜索