R
R
Rustam Bogdanov2020-03-23 18:14:12
Python
Rustam Bogdanov, 2020-03-23 18:14:12

How to add a Python variable to an SQL query?

Can you tell me how to add a variable to a query?
The project is a chat bot using dialogflow. When a certain command is received, it is necessary to write the client data to the database. How to transfer the data received from the input line to the database on MS SQL server?
I googled a little and did this:

print('Введите сообщение...')
message = input()
action = None
while True:
    action = send_message(message)
    if action == 'me.order':
        connection = pypyodbc.connect('Driver={SQL Server};'
                                      'Server=' + mySQLServer + ';'
                                      'Database=' + myDataBase + ';')

        cursor = connection.cursor()

        mySQLQuerySelect = (""" 
                        SELECT [name], [pnumber], [date]
                        FROM [dbo].[Order]
                        """)

        cursor.execute(mySQLQuerySelect)

        table = cursor.fetchall()
        clientName = input()
        print('Хорошо, ' + clientName + '. А теперь введите номер своего мобильного телефона в формате +79*********:')
        clientPhone = input()
        mySQLQueryInsert = ("""
                            INSERT INTO [dbo].[Order] ([name], [pnumber])
                            VALUES (""" + clientName + """, """ + clientPhone + """)"""
                            )
        cursor.execute(mySQLQueryInsert)
        print('Спасибо, ваши данные успешно записаны! Ожидайте звонка от специалиста в течение текущего рабочего дня')
        connection.close()
        break


But in this case I get an error
5e78d14d4bb1e005300624.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2020-04-05
@mrkaban

I didn’t work with Mysql in python, but with SQLite I do it as follows:

NameP=itemsoft['name']
s = 'SELECT * FROM program WHERE (name LIKE "' + NameP + '%%")'
CurBLpro.execute(s)
records = CurBLpro.fetchall()

but this is getting data from the database, in fact, which prevents us from making a record according to the same logic.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question