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.

1 Answer 1

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)
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.