首页 > 解决方案 > 将 python(语音识别文本)插入 SQL Server 数据库

问题描述

我使用带有 python 的语音识别应用程序,其中您所说的文本保存在名为“yourtext.txt”的文件中,我尝试将其连接到 SQL Server 数据库,结果也将添加到文本文件中如在 SQL Server 表中,voice2text.dbo.yourtext (id, 'text1')任何帮助将不胜感激。

注意:我在第 19 行的 SQL 命令中有语法错误,但我不知道如何修复它...

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 !")

标签: pythonsql-servervoice-recognition

解决方案


要从变量中加入/连接字符串,您必须使用+

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

?在执行中使用和发送文本作为参数会更安全

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

顺便说一句:execute()需要tuple有参数 - 即使你只有一个参数。它需要逗号(text,)来创建tuple。括号()不会创建tuple. 它们仅与text,该行中的其他逗号分隔。


推荐阅读