Home > Backend Development > Python Tutorial > Explanation of python basic knowledge points

Explanation of python basic knowledge points

巴扎黑
Release: 2017-06-23 11:10:02
Original
2110 people have browsed it

Section 16 MySQLdb

  • ##win64-bit installation python-mysqldb1.2.5

  • Installing MySQLdb under ubuntu

    sudo apt-get install python-MySQLdb
    Copy after login
  • Import MySQLdb library

    import MySQLdb
    Copy after login
  • Create database connection

    conn = MySQLdb.connect(host="localhost",user="root",passwd="123456",db="test",charset="utf8")
    Copy after login
  • connect object properties

    • commit(): If the database table is modified, submit to save the current data. Of course, if this user doesn't have permission and just does it, nothing will happen.

    • rollback(): If you have permission, cancel the current operation, otherwise an error will be reported.

    • cursor([cursorclass]): Cursor pointer.

  • Create a cursor (pointer) cursor

    cur = conn.cursor()
    Copy after login
  • cursor method of executing commands:

    • execute(query, args): Execute 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 affected rows.

    • executemany(query, args): Execute a single sql statement, but repeatedly execute the parameters in the parameter list, and the return value is the number of affected rows

  • Insert a record into the data table

    cur.execute("insert into users (username,password,email) values (%s,%s,%s)",("python","123456","python@gmail.com"))
    Copy after login
  • Insert multiple records into the 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")))
    Copy after login
  • Submit database operation

    conn.commit()
    Copy after login
  • Query data

    cur.execute("select * from users")
    Copy after login
    • ##fetchall(self)

      :Receive all Return result rows.

    • fetchmany(size=None)

      : Receive size return result rows. If the value of size is greater than the number of returned result rows, then Will return cursor.arraysize pieces of data.

    • fetchone()

      : Returns one result row.

    • scroll(value, mode='relative')

      : Move the pointer to a certain row. If mode='relative', it means moving the value bar from the current row. If mode='absolute', it means moving the value bar from the result set. The first line moves the value bar.<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">cur.execute(&quot;select * from users&quot;) lines = cur.fetchall() for line in lines:     print line cur.execute("select * from users where id=1") line_first = cur.fetchone()     #只返回一条 print line_first cur.execute(&quot;select * from users&quot;) print cur.fetchall()</pre><div class="contentsignin">Copy after login</div></div>

    • The method of cursor object to obtain data
    The operation of cursor
    • cur.scroll(n)

      or cur.scroll(n,"relative"): means to move up or down relative to the current position , n is a positive number, which means downward (forward), n is a negative number, which means upward (backward)

    • There is another way to achieve "absolute" movement, not " Relative" move: Add a parameter "absolute"
    • cur.scroll(1)
      cur.scroll(-2)
      cur.scroll(2,"absolute")    #回到序号是2,但指向第三条
      Copy after login

    Update data
  • cur.execute("update users set username=%s where id=2",("mypython"))
    conn.commit()
    Copy after login

  • Specify the database
  • conn = MySQLdb.connect("localhost","root","123456",port=3306,charset="utf8")    #创建数据库时不指定那个数据库
    conn.select_db("test")      #连接创建后再指定
    Copy after login

  • Close the database
  • cur.close()     #先关闭游标
    conn.close()    #再关闭数据库
    Copy after login


Section 17 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: are two important concepts in object-oriented
    • Class: is an abstraction of things, such as: car model
    • Object: is an instance of a class, such as: QQ car, bus
    Example description
    • The car model can abstract the characteristics and behavior of the car, and then instantiate a real car entity Come out
    Python class definition

    Python class definition
    • Use the class keyword to define a class, and the first letter of the class name should be capitalized
    • When programmers need to create a type that cannot be represented by a simple type, they need to create a class
    • A class combines the required variables and functions. This inclusion is also called "encapsulation"
    The structure of the Python class
  • class 类名:
        成员变量
        成员函数
    
    class MyClass():
        first = 123
        def fun(self):
            print "I am function"
    Copy after login

  • Creation of objects
    • Handles are used to distinguish different objects
    • Properties of objects And methods correspond to member variables and member functions in the class
    • if __name__ == "__main__":
          myClass = MyClass()     #创建类的一个实例
      Copy after login

    • The process of creating an object is called instantiation; when an object is created, it contains three characteristics: Object handles, properties and methods.
    Constructor __init__
  • class Person:
        def __init__(self, name, lang, website):
            self.name = name
            self.lang = lang
            self.website = website
    Copy after login

  • self is a very magical parameter
    • self points to an instance of the class. When the instance calls a method, self points to the instance of the called method
    Subclass, parent class and inheritance
  • # 抽象形状类
    class Shape:
        # 类的属性
        edge = 0
        # 构造函数
        def __init__(self, edge):
            self.edge = edge
        # 类的方法
        def getEdge(self):
            return self.edge
        # 抽象方法  
        def getArea(self):
            pass
    
    #三角形类,继承抽象形状类
    class Triangle(Shape):
        width = 0
        height = 0
        # 构造函数
        def __init__(self, width, height):
            #调用父类构造函数
            Shape.__init__(self, 3)
            self.width = width
            self.height = height
        #重写方法
        def getArea(self):
            return self.width * self.height / 2
    
    #四边形类,继承抽象形状类       
    class Rectangle(Shape):
        width = 0
        height = 0
        # 构造函数
        def __init__(self, width, height):
            #调用父类构造函数
            Shape.__init__(self, 4)
            self.width = width
            self.height = height
        #重写方法
        def getArea(self):
            return self.width * self.height
    
    triangle = Triangle(4,5);
    print triangle.getEdge()
    print triangle.getArea()
    
    rectangle = Rectangle(4,5);
    print rectangle.getEdge()
    print rectangle.getArea()
    Copy after login

  • Python supports multiple inheritance, but it is not recommended

The above is the detailed content of Explanation of python basic knowledge points. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template