First, operate the mysql database
import pymysql
# 1. Connect to the database: account, password, ip , port number, database
# 2. Create a cursor (workers who go to the database to get things)
# 3. Execute sql
# 4. Get the result
# 5. Close the cursor
# 6. The connection is closed
coon = pymysql.connect(
host='xxx.xxx.xxx.xxx',user='xxx',passwd='123456',port=3306,db='xxx',charset='utf8') ##port must be int type, charset must be is utf8 , not utf-8
cur = coon.cursor() #Create a cursor
cur.execute('select * from stu;')
cur.execute('insert into stu (id,name,sex) value (33,"6j","女")')
coon.commit() ## must commit
res = cur.fetchall() #Get all returned results
print(res)
cur.close() #Close the cursor
coon.close() #Close the database
Define database functions
1 def my_db(host,user,passwd,db,sql,port=3306,charset='utf-8'): 2 3 import pymysql 4 5 coon =pymysql.connect( 6 7 user=user,passwd=passwd,host=host,port=port, 8 9 db=db,charset=charset 10 11 ) 12 13 cur = coon.cursor() 14 15 cur.execute(sql) 16 17 if sql.strip()[:6].upper()=='SELECT': 18 19 res = cur.fetchall() 20 21 else: 22 23 coon.commit() 24 25 res = 'OK' 26 27 cur.close() 28 29 coon.close() 30 31 return res
Tips:
1. You can define variables like this: define multiple variables at once
2. When operating the database to execute sql, if the query condition is a string, first place the placeholder %s, and then write the string after it, as shown below:
res = my_db('select password from liujing where username = "%s" and password = "%s";'%(username_login,m_pwd_login))
3. Specify that the result returned by sql is a dictionary type: when creating a cursor, you can specify the cursor type to return a dictionary. What mydb returns is a list, and the content of the list is a dictionary.
cur = coon.cursor(cursor=pymysql.cursors.DicCursor)
4. fetchall() #Get all the results of this sql execution, it puts each row of data in the database table into a list
fetchone() # Get a result of this sql execution, it returns only one piece of data
If the result of SQL statement execution is multiple pieces of data, then use fetchall()
If you can be sure that the result of sql execution is a piece of data, then use fetchone()
5. To dynamically obtain the target field cur.descrption can obtain the table structure, and then obtain the fields of the table
fileds = [filed[0] for filed in cur.description]
6.enumerate([list,list2]) #When looping, you can directly get the subscript and the value represented by the subscript
fileds = ['id','name','sex','addr','gold','score']
for index,filed in enumerate(fileds):
print(index,filed) #index will automatically increase by one when looping
Second, operate excel
write excel
1 import xlwt 2 3 book = xlwt.Workbook() #Create a new excel 4 5 sheet = book.add_sheet( ' sheet1 ' ) #Add sheet page 6 7 sheet.write(0,0, ' name ' ) #First line , the first column, the written content 8 9 sheet.write(0,1, ' age ' ) #the first row, the second column, the written content 10 11 sheet.write(0,2, ' gender ' ) #The first row, the third column, the written content 12 13 book.save(' stu.xls ' ) # must end with xls
read excel
1 import xlrd 2 book = xlrd.open_workbook( ' app_student.xls ' ) #Open excel 3 sheet = book.sheet_by_index(0) #Select sheet page 4 according to the order of sheet pages sheet2 = book.sheet_by_name( ' sheet1 ' ) #According to Sheet page name select sheet page 5 print (sheet.cell(0,0).value) #Get the value of the first row and first column in the sheet page 6 print (sheet.cell(1,0).value) #Get sheet The value of the second row and the first column in the page 7 print (sheet.row_values(0)) #Get the content of the first row and the entire row, and put it in the list 8 print (sheet.row_values(1)) #Get the content of the second row and a whole row and put it in the list 9 print (sheet.nrows) #Get how many rows in excel 10 for i in range(sheet.nrows): # #loop to get the data of each row 11 print (sheet.row_values(i)) # #print the data of each row 12 print (sheet.ncols) #get how many columns there are in excel 13 print (sheet.col_values(0)) #Get the content of a whole column and put it in the list 14 for i in range(sheet.ncols): # #loop to get the data of each column 15 print (sheet.col_values(i)) # print the data of each column
modify excel
1 import xlrd 2 from xlutils import copy 3 book = xlrd.open_workbook( ' app_student.xls ' ) #Use the xlrd module first to open an excel 4 new_book = copy.copy(book) #By the copy method in the xlutils module, copy An excel 5 sheet = new_book.get_sheet(0) #Get a sheet page 6 7 through the sequence of sheet pages # #Change the field name of app_student.xls to lis = ['Number','Name','Gender',' Age', 'address', 'class', 'mobile phone number', 'gold coin'] field name 8 # sheet.write(0,0, 'number') #If there are many fields, this requires a lot of lines of code 9 # sheet.write(0,1,'name') 10 lis = [' Number ' , ' Name ' , ' Gender ' , ' Age ' , ' Address ' , ' Class ' , ' Phone number ' , ' Gold coin ' ] 11 # col=0 12 # for l in lis: 13 # sheet.write (0,col,l) 14 # col+=1 15 for col,filed in enumerate(lis): 16 sheet.write(0,col,filed) 17 new_book.save('app_student.xls')