-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path01_connect_select.py
More file actions
49 lines (36 loc) · 1.02 KB
/
01_connect_select.py
File metadata and controls
49 lines (36 loc) · 1.02 KB
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
#=======================================
# Exercise 01_connect_select
#=======================================
# Topic: connect & SELECT basics
#=======================================
#Run in terminal: pip install pyodbc pandas
import pyodbc
SERVER = '<server-address>'
DATABASE = '<database-name>'
USERNAME = '<username>'
PASSWORD = '<password>'
connectionString = f'DRIVER={{ODBC Driver 17 for SQL Server}};SERVER={SERVER};DATABASE={DATABASE};UID={USERNAME};PWD={PASSWORD}'
conn = pyodbc.connect(connectionString)
SQL_QUERY = """
SELECT
1 AS Number,
'Jane Doe' AS StudentName
UNION ALL
SELECT
2 AS Number,
'John Doe' AS StudentName
"""
cursor = conn.cursor()
cursor.execute(SQL_QUERY)
records = cursor.fetchall()
#print total resultset
print("print(records):")
print(records)
#Divider
print("\n" + "-" * 50 + "\n")
#print total resultset - formatted
#print header
print(f"Number\t""StudentName")
for r in records:
#print records
print(f"{r.Number}\t{r.StudentName}")