Basic knowledge of Python explained

Source: Internet
Author: User

16th Section MySQLdb

  • Win64 bit installation python-mysqldb1.2.5

  • Install MySQLdb under Ubuntu

    sudo apt-get install Python-mysqldb
  • Import MYSQLDB Library

    Import MySQLdb
  • Create a database connection

    conn = MySQLdb.connect (host= "localhost", user= "root", passwd= "123456", db= "test", charset= "UTF8")
  • Connect Object Properties

      • commit(): If the database table has been modified, commit to save the current data. Of course, if this user does not have permission to do it, nothing will happen.

      • rollback(): If you have permission, cancel the current operation, or an error.

      • cursor([cursorclass]): Cursor pointer.

  • Creating cursors (Pointers) cursor

    cur = conn.cursor ()
  • Cursor how to execute the command:

      • execute(query, args): Executes a single SQL statement. Query is the SQL statement itself, and args is the list of parameter values. The return value after execution is the number of rows affected.

      • executemany(query, args): Executes a single SQL statement, but repeats the parameters in the list of parameters and returns the number of rows affected

  • Insert a record in a data table

    Cur.execute ("INSERT into users (Username,password,email) VALUES (%s,%s,%s)", ("Python", "123456", "python@gmail.com")
  • Inserting multiple records in a data table

    Cur.executemany ("INSERT INTO Users" (Username,password,email) VALUES (%s,%s,%s), (("Google", "111222", "g@gmail.com"), ("Facebook", "222333", "F@face.book"), ("GitHub", "333444", "git@hub.com"), ("Docker", "444555", "doc@ker.com"))
  • Commit Database Operations

    Conn.commit ()
  • Querying data

    Cur.execute ("SELECT * from users")
      • fetchall(self): Receives all the returned result rows.

      • fetchmany(size=None): Receives a size bar to return the result row. If the value of size is greater than the number of result rows returned, the cursor.arraysize data is returned.

      • fetchone(): Returns a result row.

      • scroll(value, mode='relative'): Moves the pointer to a row. If mode= ' relative ', the value bar is moved from the current row, and if mode= ' absolute ', the value bar is moved from the first row of the result set.

        Cur.execute ("SELECT * from users") lines = Cur.fetchall () for line in lines:    print Linecur.execute ("SELECT * from Users where id=1 ") Line_first = Cur.fetchone ()     #只返回一条print line_firstcur.execute (" SELECT * from users ") print Cur.fetchall ()
      • Cursor object methods to get data

  • Cursors cursor Operations

      • cur.scroll(n)Or cur.scroll(n,"relative") : means move up or down relative to the current position, n is positive, indicates down (forward), n is negative, indicates up (backward)

      • There is also a way to achieve "absolute" movement, not "relative" movement: Add a parameter "absolute"

        Cur.scroll (1) cur.scroll ( -2) Cur.scroll (2, "absolute")    #回到序号是2, but pointing to the third article
  • Update data

    Cur.execute ("Update users set username=%s where id=2", ("Mypython")) Conn.commit ()
  • Specify the database

    conn = MySQLdb.connect ("localhost", "root", "123456", port=3306,charset= "UTF8")    #创建数据库时不指定那个数据库conn. select_db (" Test ")      #连接创建后再指定
  • Close the database

    Cur.close ()     #先关闭游标conn. Close ()    #再关闭数据库


Section 17th Object Oriented

Classes and objects

    • Process-oriented and object-oriented programming

      • Process-oriented programming: Functional programming, C-programs, etc.

      • Object-Oriented Programming: C++,java,python, etc.

    • Classes and objects: Two important concepts in object-oriented

      • Class: Is the abstraction of things, such as: Car models

      • Object: Is an instance of a class, for example: QQ sedan, bus

    • Example description

      • Car models can abstract the characteristics and behavior of a car, and then instantiate a real car entity to come out

Python class definition

  • Definition of Python class

      • Define a class using the class keyword, and capitalize the first letter of the class name

      • When a programmer needs to create a type that cannot be represented by a simple type, you need to create a class

      • Classes combine the required variables and functions, which are also known as "encapsulation"

  • Structure of the Python class

    Class Name:    member Variable    member function Class MyClass (): First    = 123    def fun (self):        print "I am function"
  • Creation of objects

      • Handles are used to distinguish between different objects

      • The properties and methods of an object correspond to member variables and member functions in a class

        if __name__ = = "__main__":    MyClass = MyClass ()     #创建类的一个实例
      • The process of creating an object is called instantiation; When an object is created, it contains three aspects of the attribute: the handle, property, and method of the object.

  • Constructor __init__

    Class Person:    def __init__ (self, name, Lang, website):        self.name = name        Self.lang = lang        self.website = website
  • Self is a very magical parameter.

      • Self points to an instance of the class, and when the instance calls the method, self points to the instance of the method that is called

  • Subclass, parent class, and inheritance

    # abstract Shape Classes Class shape: # class Properties Edge = 0 # constructor def __init_ _ (Self, edge): Self.edge = method of the Edge # class Def Getedge (self): return Self.edge # abstract method def getarea ( Self): pass# Triangle class, inheriting abstract shape class Triangle (shape): width = 0 height = 0 # constructor def __init__ (self, width, he ight): #调用父类构造函数 shape.__init__ (self, 3) Self.width = width Self.height = height #重写方法 D EF Getarea (self): return Self.width * self.height/2# Quad class, inheriting abstract shape classes class Rectangle (shape): width = 0 He  ight = 0 # constructor def __init__ (self, width, height): #调用父类构造函数 shape.__init__ (Self, 4) self.width = width Self.height = height #重写方法 def getarea (self): return self.width * self.heighttriangle = Trian GLE (4,5);p rint Triangle.getedge () print triangle.getarea () rectangle = Rectangle (4,5);p rint Rectangle.getedge () print Rectangle.getarea () 
  • Python supports multiple inheritance, but it is not recommended to use

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.