0
insert_basic = '""' + '"INSERT INTO info VALUES (' + "'" + testid + "','" + username + "','" + fullname + "','" + firstnumber + "','" + secondnumber + "','" + floatnumber + "','" + posts + "','" + country + '","' + bio + '","' + link + '");'
cur.execute(insert_basic)
try: 
    db.commit()
except:
    db.rollback()
cur.execute("""SELECT * FROM basic;""")
print cur.fetchall()

Hello, I have done a lot of research and I cannot seem to get the syntax right for submitting to SQL. Some of the variables are integers and some are strings with one being a float.

Guillaume Jacquenot
  • 11,217
  • 6
  • 43
  • 49
Ben Gitter
  • 31
  • 1

1 Answers1

2

This is what parameterized queries are for:

parameters = (testid, username, fullname, firstnumber, secondnumber, floatnumber, posts, country, bio, link)
query = """
    INSERT INTO 
        info 
    VALUES 
        (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""
cur.execute(query, parameters)

When you do it this way, you are letting your MySQL database driver to handle the type conversions between Python and MySQL automatically.

And, you are also protecting yourself from SQL injection attacks that would be easy to apply to your initial code where you string concatenate your query.


I would also specify the table column names in this case explicitly:

INSERT INTO 
    info 
    (column_name1, column_name2, ...)
VALUES
    (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195