Perform psycopg2 db search based on user input using python function


I’m trying to perform a database search, based on user input. The DBresults function in the below code is intended to catch the input stored in the “ranumber” and perform an SQL search on that specific record. I can’t seem to get this working. I’ve tried a number of things which have generated various errors, but the latest error I’m getting says “TypeError: not all arguments converted during string formatting”.
What am I missing here?

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

def DBresults(ranumber):
        conn = psycopg2.connect('dbname=reporting user=rai_user password=Rad1odsfdInd host=')
        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 = ""
            exception = 'Failure to connect to db'

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

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

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

#####Results Page

def results():
    ranumber = request.args.get('ranumber', None)
        staff = request.args.get('staff', None)

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

Here’s my file if it helps:

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()])
Asked By: nmh



Try editing

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) needs to be in tuple format for string formatting to work properly.

Answered By: cosinepenguin