1

I am trying to write a simple program to connect MySQL and perform some operations

host = '10.0.106.40'
user = 'ddddd'
port = 3306
passwd = 'DDDDDD'
db = 'bbbbbbb'

''' Creates a MySQL connection and returns the cursor '''
def create_connection():
    connection = mysql.connect(host, user, passwd, db, port)
    cursor = connection.cursor()
    return connection, cursor


''' Close the connection '''
def close_connection(cursor, connection):
    cursor.close()
    connection.commit()
    connection.close()

The above functions are my skeletons. Now, when I try to do this

for user in users:
    connection, cursor = create_connection()
    ...
    close_connection(cursor, connection)

I get this error

TypeError: connect() argument 2 must be string, not long

However, when I do this

connection, cursor = create_connection()

for user in users:    
    ...

close_connection(cursor, connection)

The code runs perfectly fine! I'm not sure but why should that be? I really want to run the earlier version of the code as the latter one is too slow for me.

0

2 Answers 2

1

My guess is that the user being passed to create_connection() is from the line

for user in users:

That is why it works outside the loop, because then it is accessing the correct user, namely the one with a String datatype.

An alternative would be to use a while loop instead or change the line to something like:

for u in users:

Or else you should do what warwaruk suggests.

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

Comments

0

users is a list of integers?

That's why it's bad to deal with globals. Better pass some parameters to create_connection instead of taking values from globals:

def create_connection(host, user, passwd, db, port):
    connection = mysql.connect(host, user, passwd, db, port)
    cursor = connection.cursor()
    return connection, cursor

2 Comments

Yes, users is a list of integers. I have tried passing parameters to the create_connection method instead of global values. So definitely the problem doesn't lie in there.
users should be a list of strings, as mysql.connect(host, user, passwd, db, port) expects second parameter - user name

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.