使用python函数基于用户输入执行psycopg2 db搜索

时间:2017-06-05 16:19:43

标签: python python-3.x flask psycopg2 flask-wtforms

我尝试根据用户输入执行数据库搜索。以下代码中的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
    )

如果有帮助,请访问我的form.py文件:

staff_choices=[("", ""), ('1', 'John Jones'), ('2', 'Chris Hughes'), ('                3', 'Lyn bear')]
class StaffNames(Form):
        ranumber = StringField('ranumber', validators=[DataRequired()])
        staff = SelectField('staff',choices=staff_choices,validators=[DataRequired()])

1 个答案:

答案 0 :(得分:1)

尝试编辑

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)需要采用元组格式才能使字符串格式化正常工作。