Python study notes thirteen _ operating database, excel

1. Operating the database

1. Install the pymysql third-party module

2. Operating the database

import pymysql
conn = pymysql.connect(
    host='xxx.xx.xx.xx', user='Amy', passwd='123456',
    port=3306, db='jxz', charset='utf8'
)
# 1. Connect to database account, password ip port number Database 
# port must be written int type 
# charset must be written in utf8, not utf-8 
cur = conn.cursor() # 2. Create a cursor 
cur.execute( ' select * from stu; ' ) # 3. Execute sql 
conn.commit() #In addition to select, other sqls need to commit 
res =cur.fetchall() # 4. Get the result print (res)

cur.close() # 5. Close the cursor 
conn.close() # 6. The connection is closed

2. Operate Excel

1. Install xlrd, xlwt third-party modules

2. Write Excel

import xlwt
book = xlwt.Workbook() #Create a new excel 
sheet = book.add_sheet( ' student information ' ) #Add sheet page 
sheet.write(0,0, ' name ' ) #row , column, written content 
sheet.write (0,1, ' age ' )
sheet.write(0, 2, ' gender ' )
book.save( ' stu.xls ' ) #must use .xls at the end

3. Read Excel

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325195545&siteId=291194637