R
R
Razer15112020-11-16 12:59:17
Python
Razer1511, 2020-11-16 12:59:17

SQL conversion error. How to fix?

Good afternoon everyone. Help solve the problem.

1. I connect to the database via pyodbc
2. I try to retrieve data from the table ( I want to get the data of the ACTIVE column from the block named 4-20 )
3. I get an error:

My code:

import pyodbc


def connect_to_base():  # Подключение к БД
    global cursor
    server = ************
    database = ************
    username = ************
    password = ************
    cnxn = pyodbc.connect(
        'DRIVER={ODBC Driver 17 for SQL Server};SERVER=' + server + ';DATABASE=' + database + ';UID=' + username +
        ';PWD=' + password)
    cursor = cnxn.cursor()


def select(column, db_table, obj):  # Чтение таблиц в БД
    cursor.execute('SELECT {} FROM {} WHERE NAME =  {}'.format(column, db_table, obj))
    row = cursor.fetchone()
    while row:
        if row[0] != False:
            print('Блок {} - активен           <<OK OK OK>>  [1/1]'.format(obj))
        else:
            print('Блок {} - неактивен         ERROR ERROR ERROR  [1/1]')
            row = cursor.fetchone()


connect_to_base()
select('ACTIVE', '[dbo].[BLAST_BLOCK]', '4-20')


5fb24c62e7e25472709075.png

After executing the select function, an error appears:

Traceback (most recent call last):
File "C:/Users/user/Desktop/Testing/123.py", line 28, in
select('ACTIVE', '[dbo].[BLAST_BLOCK ]', '4-20')
File "C:/Users/user/Desktop/Testing/123.py", line 17, in select
cursor.execute('SELECT {} FROM {} WHERE NAME = {}'. format(column, db_table, obj))
pyodbc.DataError: ('22018', "[22018] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Conversion failed when converting the nvarchar value 'NoBlock1' to data type int. (245) (SQLExecDirectW)")


I tried to convert to CAST ( {} AS NVARCHAR ), no success.
Column name, data type: nvarchar

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
o5a, 2020-11-16
@Razer1511

I'm not particularly familiar with pyodbc, but as far as I understand, the problem is passing the value without quotes, i.e. select turns out

SELECT ACTIVE FROM [dbo].[BLAST_BLOCK] WHERE NAME =  4-20

instead of correct
SELECT ACTIVE FROM [dbo].[BLAST_BLOCK] WHERE NAME =  '4-20'

It is better to use parameter passing instead of string formatting (namely for passing field values), in which case there should be no problems with types.
cursor.execute('SELECT {} FROM {} WHERE NAME =  ?'.format(column, db_table), obj)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question