一、導入模塊+建立鏈接python
import pymysql # 一、經過python去鏈接數據庫 conn = pymysql.connect(host="127.0.0.1",port=3306,user="root",passwd="admin123.",db="test_python_1",charset="utf8")
二、建立遊標,經過遊標就能夠執行sql命令mysql
# 二、建立遊標 test_cursor = conn.cursor()
三、經過遊標執行sql命令,插入一條數據sql
插入前的表的內容數據庫
執行命令fetch
# 三、執行一個插入的命令 r = test_cursor.execute("insert into test(name,age) VALUES ('999',23)")
這裏的r的值就受影響的行的數目ui
這裏要注意,若是執行修改相關的命令,則必需要commit才能生效,commit操做由數據庫鏈接的對象的操做,而不是經過遊標去執行3d
# 四、提交數據 conn.commit()
查看錶中的內容,已經多了一條數據指針
四、python的數據交互,由pymysql內部作參數傳遞對象
inp = input("請輸入姓名:") r = test_cursor.execute("insert into test(name,age) VALUES (%s,34)",inp) # 這裏能夠用字符串拼接,也可使用pymysql內部給咱們作字符串拼接 # 字符串拼接是能夠的,可是這裏禁止操做的,這裏會引發sql注入,因此不能這麼使用 print(r) # 這裏的r的意思受影響的行數
咱們看錶中的數據已經更新blog
上面只傳遞了一個參數,若是有多個參數,該怎麼傳遞呢?這裏要傳遞一個元組進去
inp = input("請輸入姓名:") inp_age = input("請輸入年齡:") r = test_cursor.execute("insert into test(name,age) VALUES (%s,%s)",(inp,inp_age))
咱們看到數據庫的表中的數據已經更新
上面的例子咱們只插入了一條數據,那麼若是咱們想一次插入多條數據該怎麼弄呢?解決辦法看下面的例子,要用excutemany命令來執行,而後經過列表或者元組把參數傳遞進去
user_info_list = [ ("cui1",23), ("cui2",24), ("cui3",25) ] r = test_cursor.executemany("insert into test(name,age) values (%s,%s)",user_info_list) print(r)
咱們能夠看到數據庫的表中已經有數據更新
四、經過pymysql更新數據庫中的內容
r = test_cursor.execute("update test set name = %s where age = 25","張國軍") print(r)
咱們能夠看到數據庫的表中的內容已經更新
五、經過pymysql刪除數據庫表中的內容
r = test_cursor.execute("delete from test where age = 25") print(r)
咱們能夠看到表中的數據已經更新
六、經過pymysql查詢數據,若是是查數據,則不須要commit
r = test_cursor.execute("select * from test") print(test_cursor.fetchone()) print(test_cursor.fetchone()) print(test_cursor.fetchmany(2)) print(test_cursor.fetchall())
咱們注意數據庫中的內容
咱們看pymysql獲得的結果
咱們能夠看到上面有一個指針的概念,第一條數據被取出來後,第二次在取數據,則就從第二條數據開始取,那麼咱們有沒有辦法移動指針呢?固然有,咱們看下面的例子
七、移動指針
絕對的方式移動指針
r = test_cursor.execute("select * from test") print(test_cursor.fetchone()) test_cursor.scroll(0,mode = "absolute") # 這裏的意思,absolute是絕對的意思,讓指針回到0的位置 print(test_cursor.fetchone())
咱們能夠看到2次取的數據是同樣的
相對的方式移動指針
r = test_cursor.execute("select * from test") print(test_cursor.fetchone()) # test_cursor.scroll(0,mode = "absolute") # 這裏的意思,absolute是絕對的意思,讓指針回到0的位置 test_cursor.scroll(2,mode="relative") # 這裏的意思,relative是相對的意思,至關當前的位置向下移動2個位置,這裏若是是負數的話,是向上移動,若是是正數,則向下移動
咱們注意數據庫中的表的順序
咱們看下pymysql執行的結果