使用python函数根据用户输入执行psycopg2数据库搜索

2024-06-25 22:46:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图根据用户输入执行数据库搜索。下面代码中的DBresults函数用于捕获存储在“ranumber”中的输入,并对该特定记录执行SQL搜索。我好像搞不好这个。我已经尝试了很多方法,但是最近的一个错误是“TypeError:不是所有参数都在字符串格式化过程中被转换”。 我错过了什么?在

def connectToDB():
        psycopg2.connect('dbname=reportingdb user=rai_gui password=Rad1oInd host=10.100.51.42')

def DBresults(ranumber):
        conn = psycopg2.connect('dbname=reporting user=rai_user password=Rad1odsfdInd host=10.100.47.42')
        cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        cur.execute("SELECT * FROM radio_archive_index_gui.radio_archive_index_gui WHERE rai_number= %s", (ranumber))
        searchresults = cur.fetchall()
        print (searchresults)


####Index Page
@app.route('/', methods=['GET', 'POST'])
@app.route('/index', methods=['GET', 'POST'])
def index():
    exception = ""
        try:
            connectToDB
        except:
            exception = 'Failure to connect to db'

        form = StaffNames()
        if not exception:
            if form.validate_on_submit():
                query = {
                    'staff': dict(staff_choices).get(form.staff.data),
                    'ranumber': form.ranumber.data
                }


                return redirect(url_for('results', **query))

        return render_template(
            'index.html', title='Search Page', exception=exception, form=form
        )

#####Results Page

@app.route('/results')
def results():
    ranumber = request.args.get('ranumber', None)
        staff = request.args.get('staff', None)
        DBresults()

        return render_template(
        'results.html', title='Results', staff=staff, ranumber=ranumber
    )

这是我的表单.py文件(如果有帮助):

^{pr2}$

Tags: formindexdefconnectpageexceptionguiresults
1条回答
网友
1楼 · 发布于 2024-06-25 22:46:22

尝试编辑

cur.execute("SELECT * FROM radio_archive_index_gui.radio_archive_index_gui WHERE rai_number= %s", (ranumber))

cur.execute("SELECT * FROM radio_archive_index_gui.radio_archive_index_gui WHERE rai_number= %s", (ranumber,))

(ranumber)必须是元组格式才能使字符串格式正常工作。在

相关问题 更多 >