0

I'm trying to login to my MySQL server that I'm running on DigitalOcean, but unfortunately I have no clue as to how to push the login through python. I've got the MySQL part implemented, but don't know how to login to the actual server itself (the computer). What other code do I need to add to accomplish this? I've already added the variables mySqlUser and mySqlPassword to the top of the file.

Here is the code I have so far:

import MySQLdb

class Database:

host = 'some ip address'
user = 'root'
password = '123'
mySqlUser = 'root'
mySqlPassword = 'someotherpassword'

db = 'test'

def __init__(self):
    self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db)
    self.cursor = self.connection.cursor()

def insert(self, query):
    try:
        self.cursor.execute(query)
        self.connection.commit()
    except:
        self.connection.rollback()



def query(self, query):
    cursor = self.connection.cursor( MySQLdb.cursors.DictCursor )
    cursor.execute(query)

    return cursor.fetchall()

def __del__(self):
    self.connection.close()


if __name__ == "__main__":

db = Database()

#CleanUp Operation
del_query = "DELETE FROM basic_python_database"
db.insert(del_query)

# Data Insert into the table
query = """
    INSERT INTO basic_python_database
    (`name`, `age`)
    VALUES
    ('Mike', 21),
    ('Michael', 21),
    ('Imran', 21)
    """

# db.query(query)
db.insert(query)

# Data retrieved from the table
select_query = """
    SELECT * FROM basic_python_database
    WHERE age = 21
    """

people = db.query(select_query)

for person in people:
    print "Found %s " % person['name']

1 Answer 1

1

You can Try this:

def __init__(self):
    self.host = 'some ip address'
    self.user = 'root'
    self.password = '123'
    self.mySqlUser = 'root'
    self.mySqlPassword = 'someotherpassword'
    self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db)
    self.cursor = self.connection.cursor()

or

def __init__(self):
    self.connection = MySQLdb.connect(host, user, password, db)
    self.cursor = self.connection.cursor()

and you batter transfer parameter when instantiation you class , instead of fixed values in class.

just a suggest and don't mind my english (:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.