-
pymysql模塊初識
-
SQL的注入問題
-
pymysql的增刪改
-
pymysql的查詢
1.pymys
ql模塊初識
import pymysql
conn = pymysql.connect(host='localhost',user='root',password='ren666666',database='test1',charset='utf8')
cursor = conn.cursor()
print('----1----')
sql = "SELECT * FROM chart1"
cursor.execute(sql)
result = cursor.fetchone()
cursor.close()
conn.close()
print(result)
sql = "SELECT * FROM chart1 where username='%s' and password='%s'"%(user,pwd) #這樣以字符串拼接會出現sql注入的問題
cursor.execute(sql)
問題以下:
假如輸入的user=uu' or 1=1 --
會發生一下狀況
select * from chart1 where username='uu' or 1=1
--' and password='%s'
#注意這裏的--是mysql中的註釋
這將會致使,即便不輸入密碼,帳號也不知道的狀況下,依然可以登錄成功
插入單個值
import pymysql
user = 1
pwd = 'pycharm'
conn = pymysql.connect(host='localhost',user='root',password='ren666666',database='test1')
cursor = conn.cursor()
print('----1----')
sql = "insert into chart1(id,name) values(%s,%s)"
cursor.executemany(sql,
[user,pwd]
)
result = cursor.fetchone()
cursor.close()
conn.close()
print(result)
#插入多個值
import pymysql
conn = pymysql.connect(host='localhost',user='root',password='ren666666',database='test1')
cursor = conn.cursor()
print('----1----')
sql = "insert into chart1(id,name) values(%s,%s)"
cursor.executemany(sql,
[(5,'pycharm'),(6,'sublime')]
)
result = cursor.fetchone()
cursor.close()
conn.close()
print(result)
4.pymysql的查詢:
import pymysql
conn = pymysql.connect(host='localhost',user='root',password='ren666666',database='test1')
cursor = conn.cursor()
print('----1----')
sql = "select * from chart1"
cursor.execute(sql)
# result = cursor.fetchone() #只能拿到一個數據
# result = cursot.fetchall() #拿到因此數據
result = cursor.fetchmany(4) #拿到4個數據
print(result)
cursor.close()
conn.close()
import pymysql
conn = pymysql.connect(host='localhost',user='root',password='ren666666',database='test1')
#cursor = conn.cursor() #這個的話會返回元組類型的結果
cursor = conn.cursor(
cursor=pymysql.cursors.DictCursor) #這個會以字典形式返回
print('----1----')
sql = "select * from chart1"
cursor.execute(sql)
result = cursor.fetchmany(4) #拿到4個數據
print(result)
cursor.close()
conn.close()
# [{'id': 1, 'name': 'python'}, {'id': 2, 'name': 'pycharm'}, {'id': 3, 'name': 'pycharm'}, {'id': 4, 'name': 'anaconda'}]