将python(语音识别文本)插入SQL Server数据库

2024-06-25 23:57:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用了一个带有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 !")

Tags: textimporttxt数据库sourcesqlserveras
1条回答
网友
1楼 · 发布于 2024-06-25 23:57:34

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

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

但在execute中使用?并将文本作为参数发送会更安全

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

顺便说一句:execute()需要tuple带参数-即使只有一个参数。它需要在(text,)中使用逗号来创建tuple。括号()不创建tuple。它们仅将text,与此行中的其他逗号分开

相关问题 更多 >