Common python libraries, python

Source: Internet
Author: User

Common python libraries, python
Sqlite3

  • Create a Cursor object to execute SQL commands. Pay attention to the security of SQL statements. In addition, for execute, executescript and executescript functions, you can directly use the Connection object to call them. The function automatically creates cursor, and return the cursor object.
    C = conn. cursor () # Never do this -- insecure! Symbol = 'rhat' c.exe cute ("SELECT * FROM stocks WHERE symbol = '% S'" % symbol) # Do this instead, note that only one element in the tuples must be followed by a comma # What is the replacement character in the SQL statement? T = ('rhat',) c.exe cute ('select * FROM stocks WHERE symbol =? ', T) print (c. fetchone () # Larger example that inserts records at a time purchases = [('2017-03-28 ', 'buy', 'ibms', 2006, 1000 ), ('2014-04-05 ', 'buy', 'msft', 2006, 1000), ('2014-04-06 ', 'clerk', 'ibm', 72.00, 53.00),] c.exe cute.pdf ('insert INTO stocks VALUES (?,?,?,?,?) ', Purchases)
  • If you use execute to execute the query statement, you can use the following method to obtain data:
    • Use cursor as an iterator and use the for statement to obtain a row of data each time.
    • Use fetchone () to obtain a row of data each time, and finally return None
    • Use fetchall () to obtain the list of rows. If no data exists, None is returned.
  • To add a python type not supported by sqlite to sqlite, you must first convert the type to be supported by sqlite. str is usually used. There are two methods:
    • Implementation class _ conform _ Method
      _ Conform _ import sqlite3class Point: def _ init _ (self, x, y): self. x, self. y = x, y def _ conform _ (self, protocol): # note that protocol if protocol is sqlite3.PrepareProtocol: return "% f; % f" % (self. x, self. y) con = sqlite3.connect (": memory:") cur = con. cursor () p = Point (4.0, -3.220.cur.exe cute ("select? ", (P,) print (cur. fetchone () [0])
    • Use sqlite3.register _ adapter to register an adapter method for the class and convert the type to str. The sqlite3 module contains a built-in python datetime type. date and datetime. datetime provides the adapter to convert them to iso.
      adapterimport sqlite3import datetimeimport timedef adapt_datetime(ts):    return time.mktime(ts.timetuple())sqlite3.register_adapter(datetime.datetime, adapt_datetime)con = sqlite3.connect(":memory:")cur = con.cursor()now = datetime.datetime.now()cur.execute("select ?", (now,))print(cur.fetchone()[0])

      You can also use sqlite3.register _ converter to register a convert method for the class and convert the value in the database to the python type. To make sqlite3 know the actual type of data queried from the database, you must set the detect_types parameter of the sqlite. connect method. The values include:
      • Declared type (implicit method)
      • By Column name (Display Method)
        detect_typeimport sqlite3class Point:    def __init__(self, x, y):        self.x, self.y = x, y    def __repr__(self):        return "(%f;%f)" % (self.x, self.y)def adapt_point(point):    return ("%f;%f" % (point.x, point.y)).encode('ascii')def convert_point(s):    x, y = list(map(float, s.split(b";")))    return Point(x, y)# Register the adaptersqlite3.register_adapter(Point, adapt_point)# Register the convertersqlite3.register_converter("point", convert_point)p = Point(4.0, -3.2)########################## 1) Using declared typescon = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)cur = con.cursor()cur.execute("create table test(p point)")cur.execute("insert into test(p) values (?)", (p,))cur.execute("select p from test")print("with declared types:", cur.fetchone()[0])cur.close()con.close()######################## 1) Using column namescon = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)cur = con.cursor()cur.execute("create table test(p)")cur.execute("insert into test(p) values (?)", (p,))cur.execute('select p as "p [point]" from test')print("with column names:", cur.fetchone()[0])cur.close()con.close()
  • Class sqlite3.Row: indicates a row of data. You can use the column name or index subscript to access the value of a column.


  • How to check the number of standard libraries that come with Python installation?

    If you win, there is a lib directory in the python installation directory.
    * For nix, it should be in/usr/lib/python2.7
     
    What are common standard libraries and third-party libraries in Python?

    There is a book about the library in the Python standard;

    To see which third-party libraries are available, visit the official website!

    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.