My program is not being able to store values in MySQL using mysql connector lib in Python

牧云@^-^@ 提交于 2020-01-03 04:33:15

问题


I was building a login/signup program in Python by using MySQL connector lib. My code wasn't able to store values in MySQL. I don't know why it is happening. When i check MySQL, then it says empty set.

Here's my code:

import mysql.connector

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd=""
)

mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE login;")

# sign up
email = input("Your email: ")
passw = input("Your password: ")
confirm_pass = input("Confirm password: ")

if passw == confirm_pass:
    print("Successfuly registered!")

    mycursor.execute("USE login;")
    mycursor.execute("CREATE TABLE id (email VARCHAR(20), passw VARCHAR(20));")

# ----------------------- This is the line ---------------------------#

    mycursor.execute(
        f"INSERT INTO id(email, passw) VALUES({email},{passw});")

# -----------------------                 ---------------------------#

else:
    print("wrong password!")

Any help would be appreciated!


回答1:


You are doing some dangerous stuff here:

No String formatting (SQL Injection)

You shouldn't use String formatting because of SQL Injection. It is also more complicated when you have larger SQL code. Use prepared Statement like:

query = "INSERT INTO id(email,passw) VALUES(%s,%s)"
args = (email, passw)
mycursor.execute(query, args)

Don't create DB/Table new all the time

Your code is destined to fail everytime because it can't create a new db with the same name if it already exist. The same with table. I would suggest to create a setup script. Also you can put the database in the connector and don't have to use mycursor.execute("USE login;")

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="",
    database='login'
)

commit

mysql connector doesn't autocommit by default see: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlconnection-commit.html

So you have to do it yourself after the execution.

mydb.commit()

The code should look like this in the end:

import mysql.connector

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="",
    database='login'
)

mycursor = mydb.cursor()

# sign up
email = input("Your email: ")
passw = input("Your password: ")
confirm_pass = input("Confirm password: ")

if passw == confirm_pass:
    print("Successfuly registered!")

    query = "INSERT INTO id(email,passw) VALUES(%s,%s)"
    args = (email, passw)
    mycursor.execute(query, args)
    mydb.commit()

else:
    print("wrong password!")


来源:https://stackoverflow.com/questions/59405740/my-program-is-not-being-able-to-store-values-in-mysql-using-mysql-connector-lib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!