5.3sqlite3

2018-05-06  本文已影响0人  钊钖

import

import sqlite3
conn = sqlite3.connect(jobs.db)

cursor object & tuple

Before we can execute a query, we need to express our SQL query as a string.

we use the Connection class to represent the database we're working with, we use the Cursor class to:

After running a query and converting the results to a list of tuples, the Cursor instance stores the list as a local variable.

A tuple is a core data structure that Python uses to represent a sequence of values, similar to a list. Unlike lists, tuples are immutable, which means we can't modify existing ones. Python represents each row in the results set as a tuple.

Python indexes Tuples from 0 to n-1, just like it does with lists. We access the values in a tuple using bracket notation.

t = ('Apple', 'Banana')
apple = t[0] 
banana = t[1]

creat a cursor and run a query

cursor = conn.cursor()

In the following code block, we:

# SQL Query as a string
query = "select * from recent_grads"
# convert the results to tuples,
# and store as a local variable
cursor.execute(query)
# Fetch the full results set as a list of tuples
results = cursor.fatchall()
#  Display the first three results
print(results[:3])
import sqlite3
conn = sqlite3.connect("jobs.db")
cursor = conn.cursor()

query = "select Major from recent_grads"
cursor.execute(query)
majors = cursor.fetchall()
print(majors[:3])

execute as a shortcut for running a query

So far, we've been running queries by creating a Cursor instance, and then calling the execute method on the instance.
The SQLite library actually allows us to skip creating a Cursor altogether by using the execute method within the Connection object itself.

conn = sqlite3.connect("jobs.db")
query = "select * from recent_grads;"
conn.execute(query).fetchall()


fetching a specific number of results

To make it easier to work with large results sets, the Cursor class allows us to control the number of results we want to retrieve at any given time. To return a single result (as a tuple), we use the Cursor method fetchone(). To return n results, we use the Cursor method fetchmany().

Each Cursor instance contains an internal counter that updates every time we retrieve results. When we call the fetchone() method, the Cursor instance will return a single result, and then increment its internal counter by 1. This means that if we call fetchone() again, the Cursor instance will actually return the second tuple in the results set (and increment by 1 again).

The fetchmany() method takes in an integer (n) and returns the corresponding results, starting from the current position. It then increments the Cursor instance's counter by n. In the following code, we return the first two results using the fetchone() method, then the next five results using the fetchmany() method.

first_result = cursor.fetchone()
second_result = cursor.fetchone()
next_five_results = cursor.fetchmany(5)
import sqlite3
conn = sqlite3.connect("jobs.db")
query = "select Major ,Major_category from recent_grads"
five_results = conn.execute(query).fetchmany(5)

close the database connection

Because SQLite restricts access to the database file when we're connected to a database, we need to close the connection when we're done working with it. Closing the connection allows other processes to access the database, which is important when you're in a production environment and working with other team members.

To close a connection to a database, use the Connection instance method close(). When we're working with multiple databases and multiple Connection instances, we want to make sure we call the close() method on the correct instance. After closing the connection, attempting to query the database using any linked Cursor instances will return the following error:

ProgrammingError: Cannot operate on a closed database.

Close the connection to the database using the Connection instance method close().

conn = sqlite3.connect("jobs.db")
conn.close()

practice

Now let's practice the entire workflow we've learned so far, from start to finish.

import sqlite3
conn= sqlite3.connect("jobs2.db")
query = '''select Major from recent_grads 

order by Major desc'''
reverse_alphabetical = conn.execute(query).fetchall()
上一篇 下一篇

猜你喜欢

热点阅读