mirror of
				https://github.com/python/cpython.git
				synced 2025-11-04 11:49:12 +00:00 
			
		
		
		
	The sqlit3.Connection object doesn't call its close() method when it's used as a context manager.
		
			
				
	
	
		
			29 lines
		
	
	
	
		
			781 B
		
	
	
	
		
			Python
		
	
	
	
	
	
			
		
		
	
	
			29 lines
		
	
	
	
		
			781 B
		
	
	
	
		
			Python
		
	
	
	
	
	
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"
 | 
						|
 | 
						|
con.close()
 |