aki2all
aki2all

Reputation: 427

Python TypeError: cannot concatenate 'str' and 'long' objects

I have few User provided information like username, password, email, etc. that user provides in a config file.

I have the parsed data from the config file using configParser module.

I want to enter these information to MySQL database.

The Data is like:

Usename="ABC"
password="ABC@1"
email="[email protected]"

My insert statement is like:

"INSERT INTO userinfo (group_ID, rank_ID, login, password, first_name, last_name, email) VALUES ('" + groupid + "', '" + rankID + "', '" + userid + "', '" + password + "', '" + fname + "', '" + lname + "', '" + email + "')"

But it is not executing, as I am getting an error:

TypeError: cannot concatenate 'str' and 'long' objects

I have tried doing: str(password), str(email) for the variables with mixed types, but no luck.

Here, group_ID and rank_ID are integers.

I have tried the following as suggested by one of the experts:

sql = "INSERT INTO userinfo (group_ID, rank_ID, login, password, first_name, last_name, email) "
"VALUES (%s, %s, %s, %s, %s, %s, %s)",
(groupid, rankID, userid, password, fname, lname, email)
try:
  c.execute(sql4)
  conn.commit()
except StandardError, e:
  print e
  conn.rollback()

But the error I get is: query() argument 1 must be string or read-only buffer, not tuple

What could be the possible solution?

Upvotes: 1

Views: 2027

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1122142

Don't interpolate values into your query yourself. Leave that to the database adapter, by using SQL parameters:

cursor.execute(
    "INSERT INTO userinfo (group_ID, rank_ID, login, password, first_name, last_name, email) "
    "VALUES (%s, %s, %s, %s, %s, %s, %s)",
    (groupid, rankID, userid, password, fname, lname, email))

The standard Python-MySQL adapter uses %s as parameter placeholders, other database adapters may use ? instead.

This has the added advantage that MySQL will figure out for you how to quote each value, prevent SQL injection attacks, and gives the database the chance to cache the query plan for the query and just slot in future values.

Upvotes: 4

Related Questions