-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathdemo.py
69 lines (53 loc) · 2.21 KB
/
demo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import os
import sys
from turbodbc import connect
def demo_pg():
# Connect to database.
# https://turbodbc.readthedocs.io/en/latest/pages/getting_started.html#establish-a-connection-with-your-database
# Either connect per data source name defined within the ODBC configuration,
# connection = connect(dsn="postgresql", server="localhost", database="testdrive", uid="crate", pwd=None)
# or connect per connection string, referencing a driver file directly.
if sys.platform == "linux":
candidates = [
# archlinux
"/usr/lib/psqlodbcw.so",
# Debian
"/usr/lib/x86_64-linux-gnu/odbc/psqlodbcw.so",
# Red Hat
"/usr/lib64/psqlodbcw.so",
]
driver_file = find_program(candidates)
if driver_file is None:
raise ValueError(f"Unable to detect driver file at {candidates}")
elif sys.platform == "darwin":
driver_file = "/usr/local/lib/psqlodbcw.so"
else:
raise NotImplementedError(f"Platform {sys.platform} not supported yet")
connection_string = f"Driver={driver_file};Server=localhost;Port=5432;Database=testdrive;Uid=crate;Pwd=;"
print(f"INFO: Connecting to '{connection_string}'")
connection = connect(connection_string=connection_string)
# Insert data.
cursor = connection.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS testdrive (id INT PRIMARY KEY, data TEXT);")
cursor.execute("DELETE FROM testdrive;")
cursor.execute("INSERT INTO testdrive VALUES (0, 'zero'), (1, 'one'), (2, 'two');")
cursor.executemany("INSERT INTO testdrive VALUES (?, ?);", [(3, "three"), (4, "four"), (5, "five")])
cursor.execute("REFRESH TABLE testdrive;")
cursor.close()
# Query data.
cursor = connection.cursor()
cursor.execute("SELECT * FROM testdrive ORDER BY id")
print("Column metadata:")
print(cursor.description)
print("Results by row:")
for row in cursor:
print(row)
cursor.close()
# Terminate database connection.
connection.close()
def find_program(candidates):
for candidate in candidates:
if os.path.exists(candidate):
return candidate
if __name__ == "__main__":
demo_pg()