Dexter
Dexter

Reputation: 11841

Python MySQL connection argument error

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.

Upvotes: 1

Views: 3584

Answers (2)

Antimony
Antimony

Reputation: 2240

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.

Upvotes: 1

warvariuc
warvariuc

Reputation: 59674

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

Upvotes: 0

Related Questions