mirror of
https://github.com/jart/cosmopolitan.git
synced 2025-06-02 02:32:27 +00:00
python-3.6.zip added from Github
README.cosmo contains the necessary links.
This commit is contained in:
parent
75fc601ff5
commit
0c4c56ff39
4219 changed files with 1968626 additions and 0 deletions
15
third_party/python/Doc/includes/sqlite3/adapter_datetime.py
vendored
Normal file
15
third_party/python/Doc/includes/sqlite3/adapter_datetime.py
vendored
Normal file
|
@ -0,0 +1,15 @@
|
|||
import sqlite3
|
||||
import datetime
|
||||
import time
|
||||
|
||||
def 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])
|
16
third_party/python/Doc/includes/sqlite3/adapter_point_1.py
vendored
Normal file
16
third_party/python/Doc/includes/sqlite3/adapter_point_1.py
vendored
Normal file
|
@ -0,0 +1,16 @@
|
|||
import sqlite3
|
||||
|
||||
class Point:
|
||||
def __init__(self, x, y):
|
||||
self.x, self.y = x, y
|
||||
|
||||
def __conform__(self, 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.2)
|
||||
cur.execute("select ?", (p,))
|
||||
print(cur.fetchone()[0])
|
17
third_party/python/Doc/includes/sqlite3/adapter_point_2.py
vendored
Normal file
17
third_party/python/Doc/includes/sqlite3/adapter_point_2.py
vendored
Normal file
|
@ -0,0 +1,17 @@
|
|||
import sqlite3
|
||||
|
||||
class Point:
|
||||
def __init__(self, x, y):
|
||||
self.x, self.y = x, y
|
||||
|
||||
def adapt_point(point):
|
||||
return "%f;%f" % (point.x, point.y)
|
||||
|
||||
sqlite3.register_adapter(Point, adapt_point)
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
cur = con.cursor()
|
||||
|
||||
p = Point(4.0, -3.2)
|
||||
cur.execute("select ?", (p,))
|
||||
print(cur.fetchone()[0])
|
20
third_party/python/Doc/includes/sqlite3/collation_reverse.py
vendored
Normal file
20
third_party/python/Doc/includes/sqlite3/collation_reverse.py
vendored
Normal file
|
@ -0,0 +1,20 @@
|
|||
import sqlite3
|
||||
|
||||
def collate_reverse(string1, string2):
|
||||
if string1 == string2:
|
||||
return 0
|
||||
elif string1 < string2:
|
||||
return 1
|
||||
else:
|
||||
return -1
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
con.create_collation("reverse", collate_reverse)
|
||||
|
||||
cur = con.cursor()
|
||||
cur.execute("create table test(x)")
|
||||
cur.executemany("insert into test(x) values (?)", [("a",), ("b",)])
|
||||
cur.execute("select x from test order by x collate reverse")
|
||||
for row in cur:
|
||||
print(row)
|
||||
con.close()
|
30
third_party/python/Doc/includes/sqlite3/complete_statement.py
vendored
Normal file
30
third_party/python/Doc/includes/sqlite3/complete_statement.py
vendored
Normal file
|
@ -0,0 +1,30 @@
|
|||
# A minimal SQLite shell for experiments
|
||||
|
||||
import sqlite3
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
con.isolation_level = None
|
||||
cur = con.cursor()
|
||||
|
||||
buffer = ""
|
||||
|
||||
print("Enter your SQL commands to execute in sqlite3.")
|
||||
print("Enter a blank line to exit.")
|
||||
|
||||
while True:
|
||||
line = input()
|
||||
if line == "":
|
||||
break
|
||||
buffer += line
|
||||
if sqlite3.complete_statement(buffer):
|
||||
try:
|
||||
buffer = buffer.strip()
|
||||
cur.execute(buffer)
|
||||
|
||||
if buffer.lstrip().upper().startswith("SELECT"):
|
||||
print(cur.fetchall())
|
||||
except sqlite3.Error as e:
|
||||
print("An error occurred:", e.args[0])
|
||||
buffer = ""
|
||||
|
||||
con.close()
|
3
third_party/python/Doc/includes/sqlite3/connect_db_1.py
vendored
Normal file
3
third_party/python/Doc/includes/sqlite3/connect_db_1.py
vendored
Normal file
|
@ -0,0 +1,3 @@
|
|||
import sqlite3
|
||||
|
||||
con = sqlite3.connect("mydb")
|
3
third_party/python/Doc/includes/sqlite3/connect_db_2.py
vendored
Normal file
3
third_party/python/Doc/includes/sqlite3/connect_db_2.py
vendored
Normal file
|
@ -0,0 +1,3 @@
|
|||
import sqlite3
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
47
third_party/python/Doc/includes/sqlite3/converter_point.py
vendored
Normal file
47
third_party/python/Doc/includes/sqlite3/converter_point.py
vendored
Normal file
|
@ -0,0 +1,47 @@
|
|||
import sqlite3
|
||||
|
||||
class 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 adapter
|
||||
sqlite3.register_adapter(Point, adapt_point)
|
||||
|
||||
# Register the converter
|
||||
sqlite3.register_converter("point", convert_point)
|
||||
|
||||
p = Point(4.0, -3.2)
|
||||
|
||||
#########################
|
||||
# 1) Using declared types
|
||||
con = 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 names
|
||||
con = 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()
|
15
third_party/python/Doc/includes/sqlite3/countcursors.py
vendored
Normal file
15
third_party/python/Doc/includes/sqlite3/countcursors.py
vendored
Normal file
|
@ -0,0 +1,15 @@
|
|||
import sqlite3
|
||||
|
||||
class CountCursorsConnection(sqlite3.Connection):
|
||||
def __init__(self, *args, **kwargs):
|
||||
sqlite3.Connection.__init__(self, *args, **kwargs)
|
||||
self.numcursors = 0
|
||||
|
||||
def cursor(self, *args, **kwargs):
|
||||
self.numcursors += 1
|
||||
return sqlite3.Connection.cursor(self, *args, **kwargs)
|
||||
|
||||
con = sqlite3.connect(":memory:", factory=CountCursorsConnection)
|
||||
cur1 = con.cursor()
|
||||
cur2 = con.cursor()
|
||||
print(con.numcursors)
|
28
third_party/python/Doc/includes/sqlite3/createdb.py
vendored
Normal file
28
third_party/python/Doc/includes/sqlite3/createdb.py
vendored
Normal file
|
@ -0,0 +1,28 @@
|
|||
# Not referenced from the documentation, but builds the database file the other
|
||||
# code snippets expect.
|
||||
|
||||
import sqlite3
|
||||
import os
|
||||
|
||||
DB_FILE = "mydb"
|
||||
|
||||
if os.path.exists(DB_FILE):
|
||||
os.remove(DB_FILE)
|
||||
|
||||
con = sqlite3.connect(DB_FILE)
|
||||
cur = con.cursor()
|
||||
cur.execute("""
|
||||
create table people
|
||||
(
|
||||
name_last varchar(20),
|
||||
age integer
|
||||
)
|
||||
""")
|
||||
|
||||
cur.execute("insert into people (name_last, age) values ('Yeltsin', 72)")
|
||||
cur.execute("insert into people (name_last, age) values ('Putin', 51)")
|
||||
|
||||
con.commit()
|
||||
|
||||
cur.close()
|
||||
con.close()
|
16
third_party/python/Doc/includes/sqlite3/ctx_manager.py
vendored
Normal file
16
third_party/python/Doc/includes/sqlite3/ctx_manager.py
vendored
Normal file
|
@ -0,0 +1,16 @@
|
|||
import sqlite3
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
con.execute("create table person (id integer primary key, firstname varchar unique)")
|
||||
|
||||
# Successful, con.commit() is called automatically afterwards
|
||||
with con:
|
||||
con.execute("insert into person(firstname) values (?)", ("Joe",))
|
||||
|
||||
# con.rollback() is called after the with block finishes with an exception, the
|
||||
# exception is still raised and must be caught
|
||||
try:
|
||||
with con:
|
||||
con.execute("insert into person(firstname) values (?)", ("Joe",))
|
||||
except sqlite3.IntegrityError:
|
||||
print("couldn't add Joe twice")
|
17
third_party/python/Doc/includes/sqlite3/execsql_fetchonerow.py
vendored
Normal file
17
third_party/python/Doc/includes/sqlite3/execsql_fetchonerow.py
vendored
Normal file
|
@ -0,0 +1,17 @@
|
|||
import sqlite3
|
||||
|
||||
con = sqlite3.connect("mydb")
|
||||
|
||||
cur = con.cursor()
|
||||
SELECT = "select name_last, age from people order by age, name_last"
|
||||
|
||||
# 1. Iterate over the rows available from the cursor, unpacking the
|
||||
# resulting sequences to yield their elements (name_last, age):
|
||||
cur.execute(SELECT)
|
||||
for (name_last, age) in cur:
|
||||
print('%s is %d years old.' % (name_last, age))
|
||||
|
||||
# 2. Equivalently:
|
||||
cur.execute(SELECT)
|
||||
for row in cur:
|
||||
print('%s is %d years old.' % (row[0], row[1]))
|
13
third_party/python/Doc/includes/sqlite3/execsql_printall_1.py
vendored
Normal file
13
third_party/python/Doc/includes/sqlite3/execsql_printall_1.py
vendored
Normal file
|
@ -0,0 +1,13 @@
|
|||
import sqlite3
|
||||
|
||||
# Create a connection to the database file "mydb":
|
||||
con = sqlite3.connect("mydb")
|
||||
|
||||
# Get a Cursor object that operates in the context of Connection con:
|
||||
cur = con.cursor()
|
||||
|
||||
# Execute the SELECT statement:
|
||||
cur.execute("select * from people order by age")
|
||||
|
||||
# Retrieve all rows as a sequence and print that sequence:
|
||||
print(cur.fetchall())
|
16
third_party/python/Doc/includes/sqlite3/execute_1.py
vendored
Normal file
16
third_party/python/Doc/includes/sqlite3/execute_1.py
vendored
Normal file
|
@ -0,0 +1,16 @@
|
|||
import sqlite3
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
cur = con.cursor()
|
||||
cur.execute("create table people (name_last, age)")
|
||||
|
||||
who = "Yeltsin"
|
||||
age = 72
|
||||
|
||||
# This is the qmark style:
|
||||
cur.execute("insert into people values (?, ?)", (who, age))
|
||||
|
||||
# And this is the named style:
|
||||
cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})
|
||||
|
||||
print(cur.fetchone())
|
12
third_party/python/Doc/includes/sqlite3/execute_3.py
vendored
Normal file
12
third_party/python/Doc/includes/sqlite3/execute_3.py
vendored
Normal file
|
@ -0,0 +1,12 @@
|
|||
import sqlite3
|
||||
|
||||
con = sqlite3.connect("mydb")
|
||||
|
||||
cur = con.cursor()
|
||||
|
||||
who = "Yeltsin"
|
||||
age = 72
|
||||
|
||||
cur.execute("select name_last, age from people where name_last=:who and age=:age",
|
||||
locals())
|
||||
print(cur.fetchone())
|
24
third_party/python/Doc/includes/sqlite3/executemany_1.py
vendored
Normal file
24
third_party/python/Doc/includes/sqlite3/executemany_1.py
vendored
Normal file
|
@ -0,0 +1,24 @@
|
|||
import sqlite3
|
||||
|
||||
class IterChars:
|
||||
def __init__(self):
|
||||
self.count = ord('a')
|
||||
|
||||
def __iter__(self):
|
||||
return self
|
||||
|
||||
def __next__(self):
|
||||
if self.count > ord('z'):
|
||||
raise StopIteration
|
||||
self.count += 1
|
||||
return (chr(self.count - 1),) # this is a 1-tuple
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
cur = con.cursor()
|
||||
cur.execute("create table characters(c)")
|
||||
|
||||
theIter = IterChars()
|
||||
cur.executemany("insert into characters(c) values (?)", theIter)
|
||||
|
||||
cur.execute("select c from characters")
|
||||
print(cur.fetchall())
|
15
third_party/python/Doc/includes/sqlite3/executemany_2.py
vendored
Normal file
15
third_party/python/Doc/includes/sqlite3/executemany_2.py
vendored
Normal file
|
@ -0,0 +1,15 @@
|
|||
import sqlite3
|
||||
import string
|
||||
|
||||
def char_generator():
|
||||
for c in string.ascii_lowercase:
|
||||
yield (c,)
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
cur = con.cursor()
|
||||
cur.execute("create table characters(c)")
|
||||
|
||||
cur.executemany("insert into characters(c) values (?)", char_generator())
|
||||
|
||||
cur.execute("select c from characters")
|
||||
print(cur.fetchall())
|
24
third_party/python/Doc/includes/sqlite3/executescript.py
vendored
Normal file
24
third_party/python/Doc/includes/sqlite3/executescript.py
vendored
Normal file
|
@ -0,0 +1,24 @@
|
|||
import sqlite3
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
cur = con.cursor()
|
||||
cur.executescript("""
|
||||
create table person(
|
||||
firstname,
|
||||
lastname,
|
||||
age
|
||||
);
|
||||
|
||||
create table book(
|
||||
title,
|
||||
author,
|
||||
published
|
||||
);
|
||||
|
||||
insert into book(title, author, published)
|
||||
values (
|
||||
'Dirk Gently''s Holistic Detective Agency',
|
||||
'Douglas Adams',
|
||||
1987
|
||||
);
|
||||
""")
|
16
third_party/python/Doc/includes/sqlite3/insert_more_people.py
vendored
Normal file
16
third_party/python/Doc/includes/sqlite3/insert_more_people.py
vendored
Normal file
|
@ -0,0 +1,16 @@
|
|||
import sqlite3
|
||||
|
||||
con = sqlite3.connect("mydb")
|
||||
|
||||
cur = con.cursor()
|
||||
|
||||
newPeople = (
|
||||
('Lebed' , 53),
|
||||
('Zhirinovsky' , 57),
|
||||
)
|
||||
|
||||
for person in newPeople:
|
||||
cur.execute("insert into people (name_last, age) values (?, ?)", person)
|
||||
|
||||
# The changes will not be saved unless the transaction is committed explicitly:
|
||||
con.commit()
|
26
third_party/python/Doc/includes/sqlite3/load_extension.py
vendored
Normal file
26
third_party/python/Doc/includes/sqlite3/load_extension.py
vendored
Normal file
|
@ -0,0 +1,26 @@
|
|||
import sqlite3
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
|
||||
# enable extension loading
|
||||
con.enable_load_extension(True)
|
||||
|
||||
# Load the fulltext search extension
|
||||
con.execute("select load_extension('./fts3.so')")
|
||||
|
||||
# alternatively you can load the extension using an API call:
|
||||
# con.load_extension("./fts3.so")
|
||||
|
||||
# disable extension loading again
|
||||
con.enable_load_extension(False)
|
||||
|
||||
# example from SQLite wiki
|
||||
con.execute("create virtual table recipe using fts3(name, ingredients)")
|
||||
con.executescript("""
|
||||
insert into recipe (name, ingredients) values ('broccoli stew', 'broccoli peppers cheese tomatoes');
|
||||
insert into recipe (name, ingredients) values ('pumpkin stew', 'pumpkin onions garlic celery');
|
||||
insert into recipe (name, ingredients) values ('broccoli pie', 'broccoli cheese onions flour');
|
||||
insert into recipe (name, ingredients) values ('pumpkin pie', 'pumpkin sugar flour butter');
|
||||
""")
|
||||
for row in con.execute("select rowid, name, ingredients from recipe where name match 'pie'"):
|
||||
print(row)
|
11
third_party/python/Doc/includes/sqlite3/md5func.py
vendored
Normal file
11
third_party/python/Doc/includes/sqlite3/md5func.py
vendored
Normal file
|
@ -0,0 +1,11 @@
|
|||
import sqlite3
|
||||
import hashlib
|
||||
|
||||
def md5sum(t):
|
||||
return hashlib.md5(t).hexdigest()
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
con.create_function("md5", 1, md5sum)
|
||||
cur = con.cursor()
|
||||
cur.execute("select md5(?)", (b"foo",))
|
||||
print(cur.fetchone()[0])
|
20
third_party/python/Doc/includes/sqlite3/mysumaggr.py
vendored
Normal file
20
third_party/python/Doc/includes/sqlite3/mysumaggr.py
vendored
Normal file
|
@ -0,0 +1,20 @@
|
|||
import sqlite3
|
||||
|
||||
class MySum:
|
||||
def __init__(self):
|
||||
self.count = 0
|
||||
|
||||
def step(self, value):
|
||||
self.count += value
|
||||
|
||||
def finalize(self):
|
||||
return self.count
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
con.create_aggregate("mysum", 1, MySum)
|
||||
cur = con.cursor()
|
||||
cur.execute("create table test(i)")
|
||||
cur.execute("insert into test(i) values (1)")
|
||||
cur.execute("insert into test(i) values (2)")
|
||||
cur.execute("select mysum(i) from test")
|
||||
print(cur.fetchone()[0])
|
8
third_party/python/Doc/includes/sqlite3/parse_colnames.py
vendored
Normal file
8
third_party/python/Doc/includes/sqlite3/parse_colnames.py
vendored
Normal file
|
@ -0,0 +1,8 @@
|
|||
import sqlite3
|
||||
import datetime
|
||||
|
||||
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
|
||||
cur = con.cursor()
|
||||
cur.execute('select ? as "x [timestamp]"', (datetime.datetime.now(),))
|
||||
dt = cur.fetchone()[0]
|
||||
print(dt, type(dt))
|
20
third_party/python/Doc/includes/sqlite3/pysqlite_datetime.py
vendored
Normal file
20
third_party/python/Doc/includes/sqlite3/pysqlite_datetime.py
vendored
Normal file
|
@ -0,0 +1,20 @@
|
|||
import sqlite3
|
||||
import datetime
|
||||
|
||||
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
|
||||
cur = con.cursor()
|
||||
cur.execute("create table test(d date, ts timestamp)")
|
||||
|
||||
today = datetime.date.today()
|
||||
now = datetime.datetime.now()
|
||||
|
||||
cur.execute("insert into test(d, ts) values (?, ?)", (today, now))
|
||||
cur.execute("select d, ts from test")
|
||||
row = cur.fetchone()
|
||||
print(today, "=>", row[0], type(row[0]))
|
||||
print(now, "=>", row[1], type(row[1]))
|
||||
|
||||
cur.execute('select current_date as "d [date]", current_timestamp as "ts [timestamp]"')
|
||||
row = cur.fetchone()
|
||||
print("current_date", row[0], type(row[0]))
|
||||
print("current_timestamp", row[1], type(row[1]))
|
13
third_party/python/Doc/includes/sqlite3/row_factory.py
vendored
Normal file
13
third_party/python/Doc/includes/sqlite3/row_factory.py
vendored
Normal file
|
@ -0,0 +1,13 @@
|
|||
import sqlite3
|
||||
|
||||
def dict_factory(cursor, row):
|
||||
d = {}
|
||||
for idx, col in enumerate(cursor.description):
|
||||
d[col[0]] = row[idx]
|
||||
return d
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
con.row_factory = dict_factory
|
||||
cur = con.cursor()
|
||||
cur.execute("select 1 as a")
|
||||
print(cur.fetchone()["a"])
|
12
third_party/python/Doc/includes/sqlite3/rowclass.py
vendored
Normal file
12
third_party/python/Doc/includes/sqlite3/rowclass.py
vendored
Normal file
|
@ -0,0 +1,12 @@
|
|||
import sqlite3
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
con.row_factory = sqlite3.Row
|
||||
|
||||
cur = con.cursor()
|
||||
cur.execute("select 'John' as name, 42 as age")
|
||||
for row in cur:
|
||||
assert row[0] == row["name"]
|
||||
assert row["name"] == row["nAmE"]
|
||||
assert row[1] == row["age"]
|
||||
assert row[1] == row["AgE"]
|
6
third_party/python/Doc/includes/sqlite3/shared_cache.py
vendored
Normal file
6
third_party/python/Doc/includes/sqlite3/shared_cache.py
vendored
Normal file
|
@ -0,0 +1,6 @@
|
|||
import sqlite3
|
||||
|
||||
# The shared cache is only available in SQLite versions 3.3.3 or later
|
||||
# See the SQLite documentation for details.
|
||||
|
||||
sqlite3.enable_shared_cache(True)
|
20
third_party/python/Doc/includes/sqlite3/shortcut_methods.py
vendored
Normal file
20
third_party/python/Doc/includes/sqlite3/shortcut_methods.py
vendored
Normal file
|
@ -0,0 +1,20 @@
|
|||
import sqlite3
|
||||
|
||||
persons = [
|
||||
("Hugo", "Boss"),
|
||||
("Calvin", "Klein")
|
||||
]
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
|
||||
# Create the table
|
||||
con.execute("create table person(firstname, lastname)")
|
||||
|
||||
# Fill the table
|
||||
con.executemany("insert into person(firstname, lastname) values (?, ?)", persons)
|
||||
|
||||
# Print the table contents
|
||||
for row in con.execute("select firstname, lastname from person"):
|
||||
print(row)
|
||||
|
||||
print("I just deleted", con.execute("delete from person").rowcount, "rows")
|
26
third_party/python/Doc/includes/sqlite3/simple_tableprinter.py
vendored
Normal file
26
third_party/python/Doc/includes/sqlite3/simple_tableprinter.py
vendored
Normal file
|
@ -0,0 +1,26 @@
|
|||
import sqlite3
|
||||
|
||||
FIELD_MAX_WIDTH = 20
|
||||
TABLE_NAME = 'people'
|
||||
SELECT = 'select * from %s order by age, name_last' % TABLE_NAME
|
||||
|
||||
con = sqlite3.connect("mydb")
|
||||
|
||||
cur = con.cursor()
|
||||
cur.execute(SELECT)
|
||||
|
||||
# Print a header.
|
||||
for fieldDesc in cur.description:
|
||||
print(fieldDesc[0].ljust(FIELD_MAX_WIDTH), end=' ')
|
||||
print() # Finish the header with a newline.
|
||||
print('-' * 78)
|
||||
|
||||
# For each row, print the value of each field left-justified within
|
||||
# the maximum possible width of that field.
|
||||
fieldIndices = range(len(cur.description))
|
||||
for row in cur:
|
||||
for fieldIndex in fieldIndices:
|
||||
fieldValue = str(row[fieldIndex])
|
||||
print(fieldValue.ljust(FIELD_MAX_WIDTH), end=' ')
|
||||
|
||||
print() # Finish the row with a newline.
|
27
third_party/python/Doc/includes/sqlite3/text_factory.py
vendored
Normal file
27
third_party/python/Doc/includes/sqlite3/text_factory.py
vendored
Normal file
|
@ -0,0 +1,27 @@
|
|||
import sqlite3
|
||||
|
||||
con = sqlite3.connect(":memory:")
|
||||
cur = con.cursor()
|
||||
|
||||
AUSTRIA = "\xd6sterreich"
|
||||
|
||||
# by default, rows are returned as Unicode
|
||||
cur.execute("select ?", (AUSTRIA,))
|
||||
row = cur.fetchone()
|
||||
assert row[0] == AUSTRIA
|
||||
|
||||
# but we can make sqlite3 always return bytestrings ...
|
||||
con.text_factory = bytes
|
||||
cur.execute("select ?", (AUSTRIA,))
|
||||
row = cur.fetchone()
|
||||
assert type(row[0]) is bytes
|
||||
# the bytestrings will be encoded in UTF-8, unless you stored garbage in the
|
||||
# database ...
|
||||
assert row[0] == AUSTRIA.encode("utf-8")
|
||||
|
||||
# we can also implement a custom text_factory ...
|
||||
# here we implement one that appends "foo" to all strings
|
||||
con.text_factory = lambda x: x.decode("utf-8") + "foo"
|
||||
cur.execute("select ?", ("bar",))
|
||||
row = cur.fetchone()
|
||||
assert row[0] == "barfoo"
|
Loading…
Add table
Add a link
Reference in a new issue