Python Forum
Connect to SQL and Select using Two Functions
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Connect to SQL and Select using Two Functions
#8
This works, but I'd still like to make the attributes more dynamic by allowing user input for the values instead of inside the code execution.

import pyodbc
import csv
import logging
import sys

class SQLConnection(object):
    """Create a database connection and perform DML"""

    # Class attribute
    driver = ''
    server = ''
    database = ''
    username = ''
    password = ''
    table = ''

    def __init__(self, server, database, username, password):

        self.server = server
        self.database = database
        self.username = username
        self.password = password
        self.driver = '{SQL Server}'
        self.trustconn = 'yes'
        self.tablename = 'HumanResources.Department'

        connectstring = 'DRIVER=%s;SERVER=%s;PORT=1433;DATABASE=%s;UID=%s;PWD=%s;' % (self.driver, self.server, self.database, self.username, self.password)
        """Initialize database connection"""

        self.connection = pyodbc.connect(connectstring)

        return

    def getcursor(self):
        return self.connection.cursor()

    def select_from_database(self):

        cursor = self.getcursor()
        cursor.execute("SELECT * FROM %s " % self.tablename)
        row = cursor.fetchone()
        while row:
            print("%s %s" % (row[0], row[1]))
            row = cursor.fetchone()
        return row

def main():
    conn = SQLConnection('server', 'database', 'username', 'password' )
    conn.select_from_database()

if __name__ == "__main__":
    main()
How can I pass values to those variables/arguments inside the class and/or at execution?
Reply


Messages In This Thread
RE: Connect to SQL and Select using Two Functions - by phillyfa - Apr-10-2020, 07:25 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  SQL select join operation in python(Select.. join) pradeepkumarbe 1 2,330 Feb-14-2019, 08:34 PM
Last Post: woooee

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020