linux常用命令-進階
阿新 • • 發佈:2022-12-04
一、簡介:
MySQL為關係型資料庫,其他關係型資料庫包括Oracle、DB2、Sql Server等等。Python操作MySQL需要使用到pymsyql模組,pip安裝即可。
二、操作MySQL步驟
1、連上資料庫(IP、埠號、使用者名稱、密碼、資料庫名)
2、建立遊標
3、執行sql
4、獲取結果
5、關閉遊標
6、關閉連線
1 import pymysql 2 conn = pymysql.connect( 3 host='192.168.1.112', 4 user='test', 5 passwd='111111', 6 port=3306, # port必須是int型別 7 db='test', 8 charset='utf8' # charset必須寫utf8,不能寫utf-8 9 ) 10 sqla = 'select * from stu limit 10;' 11 sqlb = 'insert into stu (id,name,sex) VALUE (10000,"張流量","女");' 12 cur = conn.cursor() # 建立遊標,不指定cursor型別返回的是二維元組 13 cur = conn.cursor(cursor=pymysql.cursors.DictCursor) # 建立遊標,指定cursor型別返回的是字典 14 cur.execute(sqla) # 執行sqla 15 cur.execute(sqlb) # 執行sqlb 16 conn.commit() # 執行insert、delete、update語句必須commit 17 res = cur.fetchall() # 執行所有返回的結果,fetchall返回的是一個二維陣列 18 res = cur.fetchone() # 執行所有返回的結果,fetchone返回的是第一行 19 res = cur.fetchmany(2) # 執行所有返回的結果,fetchmany傳入一個數返回多少條資料 20 res = cur.description # 返回表中每個欄位的資訊,description返回的也是一個二維陣列 21 print(res) 22 cur.close() # 關閉遊標 23 conn.close() # 關閉連線
Cursor型別:
不指定cursor型別,即:cur = conn.cursor(),則返回的結果是:((5, 'Ben', 男'), (6, 'Lily', 女')),是一個二維的元組
指定curson型別,即:cur = conn.cursor(cursor=pymysql.cursors.DictCursor),則返回的結果是:
[{'id': 5, 'name': 'Ben', 'sex': '男'}, {'id': 6, 'name': 'Lily', 'sex': '女'}]
fetchall()和fetchone()的區別:
fetchall():獲取到這個sql執行的全部結果,它把資料庫表中的每一行資料放到一個元組或字典裡面
fetchone():獲取到這個sql執行的一條結果,它返回的只是一條資料
如果sql語句執行的結果是多條資料的時候,那就用 fetchall(),如果能確定sql執行的結果只有一條,那就用fetchone()
三、封裝操作MySQL資料庫的函式
1 def my_db(sql,port=3306,charset='utf8'): 2 import pymysql 3 host,user,passwd,db = '192.168.1.112','test','111111','test' # 定義變數 4 conn = pymysql.connect(host=host, 5 user=user, 6 passwd=passwd, 7 port=port, 8 db=db, 9 charset=charset) 10 cur = conn.cursor(cursor=pymysql.cursors.DictCursor) # 建立遊標,指定cursor型別返回的是字典 11 cur.execute(sql) # 執行語句 12 if sql.strip().split()[0].upper() == 'SELECT': # 判斷sql語句是否以select開頭 13 res = cur.fetchall() 14 else: 15 conn.commit() 16 res = 'OK' 17 cur.close() # 關閉遊標 18 conn.close() # 關閉連線 19 return res
四、練習
傳入一個表名,把所有資料匯出,寫入excel檔案
1 def export_excel(table_name): 2 import pymysql,xlwt 3 conn = pymysql.connect( 4 host='118.24.3.40', 5 user='jxz', 6 passwd='123456', 7 port=3306, 8 db='jxz', 9 charset='utf8') 10 sql = 'select * from %s;'%table_name 11 cur = conn.cursor() # 建立遊標,不指定cursor型別返回的是二維元組 12 cur.execute(sql) # 執行sql 13 all_data = cur.fetchall() # 獲取表中所有資料 14 fileds = [filed[0] for filed in cur.description] # 獲取表的所有欄位存入一個list裡面 15 book = xlwt.Workbook() # 新建一個excel 16 sheet = book.add_sheet('sheet1') # 增加sheet頁 17 for col,filed in enumerate(fileds): 18 sheet.write(0,col,filed) # 將表頭寫入excel檔案中的第一行 19 row = 1 # 定義行數 20 for data in all_data: # 控制行 21 for col,filed in enumerate(data):#控制列 22 sheet.write(row,col,filed) 23 row = row + 1 # 每次寫完一行,行加1 24 book.save('%s.xls'%table_name)