5.3sqlite3

import

  • Import the sqlite3 library into the environment.
  • Then, use the sqlite3.connect() function to connect to jobs.db, and assign the Connection instance it returns to conn.
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:

  • Run a query against the database
  • Parse the results from the database
  • Convert the results to native Python objects
  • Store the results within the Cursor instance as a local variable.

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:

  • Write a basic select query that will return all of the values from the recent_grads table, and store this query as a string named query
  • Use the Cursor method execute() to run the query against our database
  • Return the full results set and store it as results
  • Print the first three tuples in the list results
# 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])
  • Write a query that returns all of the values in the Major column from the recent_grads table.
  • Store the full results set (a list of tuples) in majors.
  • Then, print the first three tuples in majors.
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)
  • Write and run a query that returns the Major and Major_category columns from recent_grads.
  • Then, fetch the first five results and store them as five_results.
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.

  • Connect to the database jobs2.db, which contains the same data as jobs.db.
  • Write and execute a query that returns all of the majors (Major) in reverse alphabetical order (Z to A).
  • Assign the full result set to reverse_alphabetical.
  • Finally, close the connection to the database.
import sqlite3
conn= sqlite3.connect("jobs2.db")
query = '''select Major from recent_grads 

order by Major desc'''
reverse_alphabetical = conn.execute(query).fetchall()
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,753评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,668评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,090评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,010评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,054评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,806评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,484评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,380评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,873评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,021评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,158评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,838评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,499评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,044评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,159评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,449评论 3 374
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,136评论 2 356

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,338评论 0 10
  • 一、颈部疾病: 一样先从概念讲起,服气的”服“字,这个概念影响颈椎。”我不服,我就不服“,这是导致颈椎病的最大心里...
    慈觉阅读 432评论 0 0
  • A端向B端发起 A需要准备1.播放等待对方接听的铃声2.等待对方接听的UI3.登录信令 并初始化声网视频配置 4....
    罗淞阅读 2,617评论 5 14
  • 2017年的情人节就这么悄无声息的来了,作为一个单身N多年,从来不知道七夕为何物的大龄剩女来说,所有的节日都毫无意...
    极品酱油阅读 483评论 0 0
  • 种树的最好时间是十年前,其次是现在。这是我看完《通往财富的自由之路》本周内容的第一反应。 李笑来创造了个概念,“最...
    海涛笔记阅读 334评论 0 4