1. 程式人生 > 實用技巧 >python操作mysql資料庫

python操作mysql資料庫

1.需要安裝第三方庫 import pymysql

===============1.增刪改查==============

import pymysql
#格式:pymysql.connect(mysql伺服器地址,使用者名稱,密碼,資料庫名,編碼)
database = pymysql.connect('127.0.0.1','root','root','rk18',port=3307,charset = 'utf8')
#初始化指標
cursor = database.cursor()
#====增====
#格式:"insert into 表名(欄位1,欄位2,欄位3) values(內容1,內容2,內容3)"
#sql = "insert into score(name,lilun,jineng) values('小露露',98,90)" #====修改==== #格式:"update 表名 set 欄位1=內容1,欄位2=內容2 where 條件" #sql = "update score set lilun=99 where id=30" #====刪除==== sql = "delete from score where id>34" cursor.execute(sql) database.commit() database.close() #====查詢==== #格式:"select 欄位 from 表名 where 條件"
""" sql = "select name,lilun,jineng from score where id>30" cursor.execute(sql) result = cursor.fetchall() print(result) """

===========2.將資料庫中的資料拷貝到excel檔案中========

import xlwt,xlrd
from xlutils.copy import copy
import pymysql
database = pymysql.connect('127.0.0.1','root','root','rk18',port=3307,charset='
utf8') cursor = database.cursor() sql = 'select name,count(name),sum(lilun),sum(jineng) from score group by name' cursor.execute(sql) result = cursor.fetchall() #print(result) for i in result: if i[0] == '李曉奎': a_name = '李曉奎' a_num = i[1] a_lilun = i[2] a_jineng = i[3] elif i[0] == '曾晨': b_name = '曾晨' b_num = i[1] b_lilun = i[2] b_jineng = i[3] # 新建立一個文件薄 #new_workbook = xlwt.Workbook() #work_sheet = new_workbook.add_sheet('目錄')
#複製檔案簿
tem_excel = xlrd.open_workbook('d:/test1.xls',formatting_info=True) #tem_sheet = tem_excel.sheet_by_index(0) new_workbook = copy(tem_excel) work_sheet = new_workbook.get_sheet(0) style = xlwt.XFStyle() font = xlwt.Font() font.name = '微軟雅黑' font.bold = True font.height = 360 style.font = font borders = xlwt.Borders() borders.top = xlwt.Borders.THIN borders.bottom = xlwt.Borders.THIN borders.left = xlwt.Borders.THIN borders.right = xlwt.Borders.THIN style.borders = borders alignment = xlwt.Alignment() alignment.horz = xlwt.Alignment.HORZ_CENTER alignment.vert = xlwt.Alignment.VERT_CENTER style.alignment = alignment work_sheet.write(1,0,a_name,style) work_sheet.write(1,1,a_num,style) work_sheet.write(1,2,a_lilun,style) work_sheet.write(1,3,a_jineng,style) work_sheet.write(2,0,b_name,style) work_sheet.write(2,1,b_num,style) work_sheet.write(2,2,b_lilun,style) work_sheet.write(2,3,b_jineng,style) new_workbook.save('d:/test4.xls')