Querying a list of tuples in Database

后端 未结 1 842
臣服心动
臣服心动 2021-01-29 08:15

Since I am new to python programming, I don’t know more about querying a data from a database. First, I’ve created my database in SQL Server, with 2 columns: The String

相关标签:
1条回答
  • 2021-01-29 08:40

    Your query is not clear for me. You mix SQL data structures and Python data structures and it is not clear if this will be called from Python or from SQL. Your query should contain some code you are trying to execute.

    With such a simple data in your SQL tables you can think of SQL tables as of Python dictionaries. NUMSTR dict represents you first SQL table, and I change X list of tuples into dict:

    NUMSTR = {1: 'one', 2: 'two', 3: 'three'}
    X = {'three': 'odd', 'one': 'odd', 'two': 'even'}
    
    def show_even_odd(in_numbers):
        numbers_info = []
        for i in in_numbers:
            try:
                num_name = NUMSTR[i]
                eo = X[num_name]
            except KeyError:
                eo = '???'
            numbers_info.append(eo)
        print(' | '.join(['%4s' % x for x in numbers_info]))
        print(' | '.join(['%4s' % x for x in in_numbers]))
    
    
    def test():
        show_even_odd([1, 2, 3])
    

    I stored data in numbers_info to display it in one line. It would be easier to show info about each number in separate line.

    EDIT

    If your problem is to get first value of each tuple and display its numeric value then such code looks like:

    X = [('three','odd'), ('one','odd'), ('two','even')]
    for nn, eo in X:
        print('%s - %s' % (get_number(nn), eo))
    

    Now you must define get_number() function. With global cursor this may work:

    def get_number(number_name):
        result = number_name
        cursor.execute('SELECT numeric FROM my_table WHERE String = ?', number_name)
        for txt in cursor.fetchall():
            result = txt[0]
        return result
    

    PS In this code I used ? in SELECT to make prepared statement. It should be replaced with number_name by ODBC driver. Such operation can be done by Python: "SELECT ... WHERE String = '%s'" % (number_name), but prepared statements are much better. They prevent against SQL Injection and database can better cache query plan for such statements.

    0 讨论(0)
提交回复
热议问题