Learning module 005 recording / write Excel / database operation

[Concept of modules]

A standard module ----> python carrying module, is mounted directly into the python can be used, such as time and the like os

2 third-party modules ----> pymysal need to be installed in

3 Write your own python file ----> a python file is a module

4 Pour the substance modules ----> it is to pour the module file from start to finish to run again

Pour the order of 5 modules ----> poured into a module first looks in the current path, and if not then the python environment variable file directory to find, if not the error

 View python path environment variable which:

Import SYS
 Print (sys.path)   # View python environment variable path, into the module long as there is one in which the error will not, do not, then it will error

6 pycharm tool to find modules are not looking in the current directory, so the module monogram in red poured into the current path, but does not affect use

7 scenes, there are two projects, A and B next project, you need to perform file import module is not below B, but A below, then that does not need to pour the module is not in the current environment in python path variables inside, but in another file path, how to solve it?

  There is a need to want to pour the file path modules currently belong added inside python environment variables, add two ways, are implemented in code as follows:

import sys

# Here to add a one-time, if the latter need to find it, you need to add a 
sys.path.append ( " here is the need to pour the file path module currently belongs " ) # add the first method, which Add mode is added to the last position python environment variable file
sys.path.insert (0, r " here is the need to pour the file path module currently belongs " )    # The second method is added, but the location is specified in the path of the output list inside to add, first search

8 on which code file "if__name __ == '__ main__' "

Wrote that line its own file code: Run unaffected

Do not pour the current file when the other modules, this line of code to perform the following content is not only execute this line of code above section

[Operation] mysql

import pymysql

# The following information is connected to the database required 
# ip Port the User password db 
# 166.25.3.55 3306 123456 ZZZ ZZZ



# The first step: to establish a connection 
conn = pymysql.connect (Host = " 166.25.3.55 " , the User = " ZZZ " , password = " 123456 " , db = " ZZZ " ,
                       port = 3306, charset = " utf8 " , True autocommit =)    # the last one just added, then the following commit can be removed, the role is automatically submitted 
# Note: password must be a string, an integer port too, which also port you can not write, have default values 

CUR = conn.cursor (pymysql.cursors.DictCursor) # establish cursor


# View inside the database data before 10 
SQL = " the SELECT * from app_student limit 10 "


# Below this is an operation to add data to the database sql command 
# SQL1 = "INSERT app_student (` name`, sex` `,` age`, addr` `,` grade`, phone` `,` gold`) values ( 'Guo and so on', 'female', '26', 'Jiyuan City, Henan Province, 32 North Avenue,' 'Aquarius', '18631706666', '100'); "


cur.execute (sql)    # can only help you execute sql statement, but can not output 
# conn.commit () # If delet statement or update statement or insert statement, then the operation of the database when it needs to commit

Print (cur.fetchall ())     # Getting Results sql statement execution, return two-dimensional array (()) 
# Print (cur.fetchone ()) # Take a piece of data, return to one-dimensional array () 
# Print (cur.fetchmany (10)) # can be taken in accordance with the number of pieces of data inside a digital, two-dimensional array returns 
cur.close ()
conn.close()

 

Note entry:

When a connection is established, the user name and password must be entered as a string; port must be an integer, you can not write, because there is a default value;

2 Code aotucommit = True: when the role of database ---- insert or delete operation like, will be submitted automatically operated to code the results returned to the user

3 on the establishment of a cursor: to set up user data buffer, storing the results of sql statement

  The last time the establishment of the end of the cursor must first close the cursor and connection: cur.close () conn.close ()

4 execution result in the cursor inside, execute sql command: cur.execute (sql statement), can only execute the statement, but can not get the results

5 So if you take the result, then we need to output, then the output can be divided into three forms of output ==== "

  001 print (cur.fetchall ()) # Getting Results sql statement is executed, the result returned is a two-dimensional array: [()] tuple type

  002 print (cur.fetchone ()) # outputs execution result to the first data sql statement, just take a return is a one-dimensional array :()

  003 print (cur.fetchmany (2)) # can be performed according to the results of the sql statement inside the digital strip number of returns, the return is a two-dimensional array

About 6 Code: conn.commit (): If you insert or update operation is performed against the database, delete and other operations when it needs to commit for the connection, mention the purpose of the database update operations

  If it was in the beginning when the connection: aotucommit = True operations, these words do not have to write a consistent role in both, but the former will automatically be submitted, which will be submitted once again to perform

7 only executed sql, can output

8 see the results of running the code in time, if there is an error message: you have an error message error in your SQL syntax, is sql syntax error

9 sql statement execution delete insert update and other statements when there is no output of execution

If you want to output the result of 10 is a dictionary type, then specify the output format where is it?

   When the establishment of the cursor, specify a cursor type: pymysql.cursors.DictCursor to

[Classification] installation module

# Third-party modules, in the presence of a network connection, the following command input terminal to download and install: 
# 1 PIP the install module 
# Manual installation without a network connection: 
#    1 file download .whl 
#         PIP the install file Download path 
# For example: I want to install third-party modules to download pypi source, followed by the terminal: pip install + absolute path you want to install the module to 
#    2 Download .tar.gz file 
#         1 unzip 
#         2 setup.py install into the directory execute Python 
# For example: for example, in the pymysql.tar.gz pypi source download file you want to install, first of all first extract, then enter the unpacked directory in a terminal, enter: python setup. py install to



# Scenario: If you change your computer to reinstall python, then such a module also need to reinstall, you can which modules use the following methods to view installed to export for easy viewing 
# see which modules are currently installed 
# terminal input: PIP List 
# If the + more one by one to see a lot, you can use the pipe symbol: pip list | more


# The module currently installed third party to which a document which listed: 
# looking at the terminal position, or directly operating in a path 
# PIP Freeze> Here is the name of the file, for example: .text third party modules ----- > this leads up to the third-party modules listed files and the corresponding version number 
# scenarios: What if listed too, still need to manually enter the command to install, then there is no convenient way to time the documents inside all of the modules are installed on it? 
# PIP install -r filename The file name filename # specified file, batch file to install the module in

 [Operating table - Read Only]

Import xlrd    # module to read the table need to pour: You can only read but not write



Book = xlrd.open_workbook ( "personnel list .xlsx " )    # Open Table: If the file name can be directly input file in the current directory, if not in the current directory, enter the absolute path to 
sheet1 book.sheet_by_index = (0)         # be acquired according to the subscript sheet page of the current page in which sheet 
Sheet2 = book.sheet_by_name ( " work " )      # You can also get the current page in which the sheet under the name sheet page

Print (sheet2.row_values (0))    # Get the current page number of rows of data sheet 
Print (sheet2.col_values (0))    # Get the current page number column data sheet 
Print (sheet2.cell (2,1) .Value)    # you want to get the specified cell position input sheet output row and column subscripts


Print (sheet2.nrows)    # get how many rows sheet page 
Print (sheet2.ncols)    # get how many columns sheet page

[Operating table - Write-only]

Import xlwt    # write only for the new table


Book = xlwt.Workbook ()     # create a new Excel 
sheet = book.add_sheet ( " staff list " )    # create a new sheet page 
sheet.write (0, 0, " name " )
sheet.write ( 1,0, " Guo etc. " )
sheet.write (0, 1, " forms of learning " )
sheet.write(1,1,"现场")
sheet.write(0,2,"测试")

book.save ( " students.xls " )  
 # I write here is the relative path in the current directory, you can also write an absolute path, file name is written here 
# save time and finally, if you are using Microsoft office, on the use XLS 
# If wps, on the use of .xls or .xlsx end

[Operating table - Modify]

# Table inside content, modify or add data inside the 
Import xlutils, xlrd
 from xlutils Import Copy    # Pour functions from the file

# Ideas: 
# 1 Open Table 
# 2 must copy 
# 3 modifications 

Book = xlrd.open_workbook ( " enumeration function 007 exercises .xls " )    # first open table 
new_book = copy.copy (Book)    # have to bear a value, modified on the basis of the copy of this document


# Obtain sheet page which follows the subscript following; 
# Second, you also get to see the sheet according to the subscript page, why not use this method .sheet_by_index it? Because new_book copy is used in the method of this module xlutils, 
# but without xlutils .sheet_by_index this method, but this method has .getsheet 
Sheet = new_book.get_sheet (0)

title = [ " No. " , " name " , " address " , " phone number " , " sex " ]    # what you want to add to the table as a list 
for index, value in the enumerate (title):
    sheet.write(0,index,value)


new_book.save ( " enumeration function 007 exercises .xls " )    # the last saved, you can name the same

 

Guess you like

Origin www.cnblogs.com/guodengdeng/p/11080453.html