python豆瓣mysql_python操作mysql
pymysql:python操作mysql
安裝pymysql
>: pip3 install pymysql
增刪改查
# 選取操作的模塊 pymysql
# pymysql連接數(shù)據(jù)庫的必要參數(shù):主機、端口、用戶名、密碼、數(shù)據(jù)庫
# 注:pymysql不能提供創(chuàng)建數(shù)據(jù)庫的服務,數(shù)據(jù)庫要提前創(chuàng)建
import pymysql
# 1)建立數(shù)據(jù)庫連接對象 conn
# 2)通過 conn 創(chuàng)建操作sql的 游標對象
# 3)編寫sql交給 cursor 執(zhí)行
# 4)如果是查詢,通過 cursor對象 獲取結果
# 5)操作完畢,端口操作與連接
# 1)建立數(shù)據(jù)庫連接對象 conn
conn = pymysql.connect(user='root', passwd='root', database='oldboy')
# conn = pymysql.connect(user='root', passwd='root', database='oldboy', autocommit=True)
# 2)通過 conn 創(chuàng)建操作sql的 游標對象
# 注:游標不設置參數(shù),查詢的結果就是數(shù)據(jù)元組,數(shù)據(jù)沒有標識性
# 設置pymysql.cursors.DictCursor,查詢的結果是字典,key是表的字段
cursor = conn.cursor(pymysql.cursors.DictCursor)
# 3)編寫sql交給 cursor 執(zhí)行
創(chuàng)建表
# 創(chuàng)建表
sql1 = 'create table t1(id int, x int, y int)'
cursor.execute(sql1)
增
sql2 = 'insert into t1 values(%s, %s, %s)'
# 增1
cursor.execute(sql2, (1, 10, 100))
cursor.execute(sql2, (2, 20, 200))
# 重點:在創(chuàng)建conn對象時,不設置autocommit,默認開啟事務,增刪改操作不會直接映射到數(shù)據(jù)庫中,
# 需要執(zhí)行 conn.commit() 動作
conn.commit()
# 增多
cursor.executemany(sql2, [(3, 30, 300), (4, 40, 400)])
conn.commit()
刪
sql3 = 'delete from t1 where id=%s'
cursor.execute(sql3, 4)
conn.commit()
改
sql4 = 'update t1 set y=666 where id=2'
cursor.execute(sql4)
conn.commit()
查
sql5 = 'select * from t1'
row = cursor.execute(sql5) # 返回值是受影響的行
print(row)
# 4)如果是查詢,通過 cursor對象 獲取結果
# fetchone() 偏移一條取出,fetchmany(n) 偏移n條取出,fetchall() 偏移剩余全部
r1 = cursor.fetchone()
print(r1)
r2 = cursor.fetchone()
print(r2)
r3 = cursor.fetchmany(1)
print(r3)
r4 = cursor.fetchall()
print(r4)
# 5)操作完畢,端口操作與連接
cursor.close()
conn.close()
游標操作
import pymysql
from pymysql.cursors import DictCursor
# 1)建立數(shù)據(jù)庫連接對象 conn
conn = pymysql.connect(user='root', passwd='root', db='oldboy')
# 2)通過 conn 創(chuàng)建操作sql的 游標對象
cursor = conn.cursor(DictCursor)
# 3)編寫sql交給 cursor 執(zhí)行
sql = 'select * from t1'
# 4)如果是查詢,通過 cursor對象 獲取結果
row = cursor.execute(sql)
if row:
r1 = cursor.fetchmany(2)
print(r1)
# 操作游標
# cursor.scroll(0, 'absolute') # absolute絕對偏移,游標重置,從頭開始偏移
cursor.scroll(-2, 'relative') # relative相對偏移,游標在當前位置進行左右偏移
r2 = cursor.fetchone()
print(r2)
# 5)操作完畢,端口操作與連接
cursor.close()
conn.close()
pymysql事務
import pymysql
from pymysql.cursors import DictCursor
conn = pymysql.connect(user='root', passwd='root', db='oldboy')
cursor = conn.cursor(DictCursor)
try:
sql = 'create table t2(id int, name char(4), money int)'
row = cursor.execute(sql)
print(row)
except:
print('表已創(chuàng)建')
pass
# 空表才插入
row = cursor.execute('select * from t2')
if not row:
sql = 'insert into t2 values(%s,%s,%s)'
row = cursor.executemany(sql, [(1, 'tom', 10), (2, 'Bob', 10)])
conn.commit()
# 可能會出現(xiàn)異常的sql
"""
try:
sql1 = 'update t2 set money=money-1 where name="tom"'
cursor.execute(sql1)
sql2 = 'update t2 set moneys=money+1 where name="Bob"'
cursor.execute(sql2)
except:
print('轉賬執(zhí)行異常')
conn.rollback()
else:
print('轉賬成功')
conn.commit()
"""
解決
try:
sql1 = 'update t2 set money=money-1 where name="tom"'
r1 = cursor.execute(sql1)
sql2 = 'update t2 set money=money+1 where name="ruakei"' # 轉入的人不存在
r2 = cursor.execute(sql2)
except:
print('轉賬執(zhí)行異常')
conn.rollback()
else:
print('轉賬沒有異常')
if r1 == 1 and r2 == 1:
print('轉賬成功')
conn.commit()
else:
conn.rollback()
sql注入問題和解決
import pymysql
from pymysql.cursors import DictCursor
conn = pymysql.connect(user='root', passwd='root', db='oldboy')
cursor = conn.cursor(DictCursor)
try:
sql = 'create table user(id int, name char(4), password char(6))'
row = cursor.execute(sql)
print(row)
except:
print('表已創(chuàng)建')
pass
# 空表才插入
row = cursor.execute('select * from user')
if not row:
sql = 'insert into user values(%s,%s,%s)'
row = cursor.executemany(sql, [(1, 'tom', '123'), (2, 'bob', 'abc')])
conn.commit()
# 用戶登錄
usr = input('usr: ')
pwd = input('pwd: ')
# 自己拼接參數(shù)一定有sql注入,將數(shù)據(jù)的占位填充交給pymysql
"""
sql = 'select * from user where name="%s" and password="%s"' % (usr, pwd)
row = cursor.execute(sql)
if row:
print('登錄成功')
else:
print('登錄失敗')
"""
# 知道用戶名時
# 輸入用戶時:
# tom => select * from user where name="tom" and password="%s"
# tom" # => select * from user where name="tom" #" and password="%s"
# 不自定義用戶名時
# " or 1=1 # => select * from user where name="" or 1=1 #" and password="%s"
解決注入問題
sql = 'select * from user where name=%s and password=%s'
row = cursor.execute(sql, (usr, pwd))
if row:
print('登錄成功')
else:
print('登錄失敗')
索引
索引就是 鍵 - key
1)鍵 是添加給數(shù)據(jù)庫表的 字段 的
2)給表創(chuàng)建 鍵 后,該表不僅會形參 表結構、表數(shù)據(jù),還有 鍵的B+結構圖
3)鍵的結構圖是需要維護的,在數(shù)據(jù)完成增、刪、改操作時,只要影響到有鍵的字段,結構圖都要維護一次
所以創(chuàng)建鍵后一定會降低 增、刪、改 的效率
4)鍵可以極大的加快查詢速度(開發(fā)需求中,幾乎業(yè)務都和查有關系)
5)建立鍵的方式:主鍵、外鍵、唯一鍵、index
import pymysql
from pymysql.cursors import DictCursor
conn = pymysql.connect(user='root', passwd='root', db='oldboy')
cursor = conn.cursor(DictCursor)
# 創(chuàng)建兩張表
# sql1 = """create table a1(
# id int primary key auto_increment,
# x int,
# y int
# )"""
# cursor.execute(sql1)
# sql2 = """create table a2(
# id int primary key auto_increment,
# x int,
# y int,
# index(x)###############索引,對x的索引,增加索引,提高查詢率。
# )"""
# cursor.execute(sql2)
# 每個表插入5000條數(shù)據(jù)
# import random
# for i in range(1, 5001):
# x = i
# y = random.randint(1, 5000)
# cursor.execute('insert into a1(x, y) values(%s, %s)', (x, y))
# cursor.execute('insert into a2(x, y) values(%s, %s)', (x, y))
#
# conn.commit()
import time
# a1的x、a1的id、a2的x
b_time = time.time()
sql = 'select * from a1 where id=4975'
cursor.execute(sql)
e_time = time.time()
print(e_time - b_time)
b_time = time.time()
sql = 'select * from a1 where x=4975'
cursor.execute(sql)
e_time = time.time()
print(e_time - b_time)
b_time = time.time()
sql = 'select * from a2 where x=4975'
cursor.execute(sql)
e_time = time.time()
print(e_time - b_time)
總結
以上是生活随笔為你收集整理的python豆瓣mysql_python操作mysql的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux中的SELinux与chcon
- 下一篇: loadrunner简介