首页 > 解决方案 > 如何在python代码中的sql查询中使用Input语句

问题描述

我真的在这里挣扎..所以立即帮助将不胜感激。明天必须提交一个项目。如果这个问题被重复,请把答案的链接发给我。

编码:

if user_input==4:
    station_name_p=input("name of station you want details of?")
    mydb=mysql.connector.connect(host="localhost",user="root",passwd="",database="railways")
    mycursor=mydb.cursor()
    mycursor("select * from station where Station_name=station_name_p")
    for n in mycursor:
            print(n)

这里有什么错误?Python 没有显示错误,也没有显示输出。

我在铁路数据库中有一个带有 Station_name 列的表站

标签: pythonpython-3.xmysql-connector-python

解决方案


Quick fix:

if user_input==4:
    station_name_p=input("name of station you want details of?")
    mydb=mysql.connector.connect(host="localhost",user="root",passwd="",database="railways")
    mycursor=mydb.cursor()
    mycursor.execute(f"select * from station where Station_name={station_name_p}")
    myresult = mycursor.fetchall()
    for n in myresult:
        print(n)

But be careful you should never directly insert user input into a Query. You should always escape and validate input. Research about Query prepare and SQL injection.


推荐阅读