๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Python/DB

[Python] SQL Server (pyodbc)

๋ฐ˜์‘ํ˜•

 

 

local

class Database():
    def __init__(self):
        self.server = 'localhost'
        self.database = 'adb'
        self.cnxn = pyodbc.connect('Trusted_Connection=yes', DRIVER=self.driver, SERVER=self.server, PORT=1433, DATABASE=self.database)

 

import pyodbc
import pandas as pd

class aDb():
    def __init__(self):
        self.server = '130.1.1.1'
        self.database = 'adb'
        self.username = 'sa'
        self.password = '1234'
        self.driver = '{ODBC Driver 17 for SQL Server}'
        self.cnxn = pyodbc.connect(f'''DRIVER={self.driver};
                                    SERVER={self.server};
                                    PORT=1433;DATABASE={self.database};
                                    UID={self.username};
                                    PWD={self.password}''')
        
    def get_data(self, sql):
        dataset = pd.read_sql(sql, self.cnxn)
        return dataset
    
    def run_sql(self, sql):
        cursor = self.cnxn.cursor()
        cursor.execute(sql)
        cursor.commit()
        
    def close(self):
        self.cnxn.close()
        
        
db = aDb()
df = db.get_data('SELECT * FROM USER')
๋ฐ˜์‘ํ˜•