-
Notifications
You must be signed in to change notification settings - Fork 3
/
Examples.py
70 lines (53 loc) · 1.93 KB
/
Examples.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
70
import pyodbc
import pandas as pd
config = dict(
driver = '{SQL Server}',
server = 'tcp:brkressql01.database.windows.net',
database = 'BRKRes01',
username = '<your username>' ,
password = '<your password>')
conn_str = ('DRIVER={driver};'+
'SERVER={server};'+
'DATABASE={database};'+
'UID={username};'+
'PWD={password}')
cnxn = pyodbc.connect(conn_str.format(**config))
# cnxn = pyodbc.connect('DRIVER={ODBC DRIVER 17 for SQL Server};SERVER='+
# server +';DATABASE=' + database +
# ';UID=' + username +
# ';PWD=' + password)
#cnxn = pyodbc.connect('DSN={SQLBrookings};Database=BRKRes01;UID=<your username>;PWD=<your password>')
cursor = cnxn.cursor()
cursor.execute("select top 10 * from CRS1;")
#[column[0] for column in cursor.description]
pd.read_sql_query("select top 10 * from CRS1", cnxn)
for entry in cursor:
print(entry)
donors = pd.read_sql('select * from Donors', cnxn)
query = '''SELECT
YEAR, SUM(Value) AS Total
FROM CRS1
WHERE
CRS1.DONOR IN (SELECT DONOR FROM Donors WHERE DDescription='United States') AND
CRS1.RECIPIENT IN (SELECT RECIPIENT FROM Recipients WHERE RDescription='India') AND
CRS1.SECTOR IN (SELECT SECTOR from Sectors WHERE SDescription='Total All Sectors')
GROUP BY YEAR ORDER BY YEAR;'''
test = pd.read_sql(query, cnxn)
test.head()
# Find available tables
for table_name in cursor.tables(tableType='TABLE'):
print(table_name)
# Find fields in table CRS1
pd.read_sql_query('select top 1 * from CRS1', cnxn).columns
# Upload a table to the DATABASE
import seaborn as sns
iris = sns.load_dataset('iris')
import sqlalchemy
import urllib
params = urllib.parse.quote_plus(conn_str.format(**config))
engine = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect={}".format(params), echo=False)
iris.to_sql('Iris', engine, if_exists='replace', index = False)
pd.io.sql.get_schema(iris.reset_index(),'Iris')
cursor.execute('drop table Iris')
cursor.commit()
cnxn.close()