Search code examples
pythonsql-servervoice-recognition

Insert python (voice recognition text) to SQL Server database


I used a voice recognition app with python where the text of what you say is saved in a file named "yourtext.txt", and I tried to connect it to a SQL Server database where the result will be added in the text file as well as in the SQL Server table voice2text.dbo.yourtext (id, 'text1') any help would be appreciated.

Note : I have a syntax error in the SQL command on line 19, but I don't know how to fix it...

import speech_recognition as sr
import pyaudio
import pyodbc

r = sr.Recognizer()

with sr.Microphone() as source :
    print("Say Something, pwease :")
    audio = r.listen(source)
    try :
        text = r.recognize_google(audio, language="fr-FR")
        conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=VEGA\SQLEXPRESS;'
                      'Database=voice2text;'
                      'Trusted_Connection=yes;')
        cursor = conn.cursor()
        sqlcommand = (" insert into yourtext values ('"text"')")
        cursor.execute(sqlcommand)
        conn.commit()
        conn.close()
        print(text,file = open("yourtext.txt","a"))
    except :
        print("Sorry, could not hear !")

Solution

  • To join/concatenate string from variable you have to use +

    sqlcommand = " insert into yourtext values ('" + text + "')"
    

    but it would be safer to use ? and send text as argument in execute

    execute("INSERT INTO yourtext VALUES (?)", (text,) )
    

    BTW: execute() needs tuple with arguments - even if you have only one argument. And it needs comma in (text,) to create tuple. Parenthesis () doesn't create tuple. They only separate text, from other comma in this line.