简体   繁体   English

如何使用用户输入查询 SQL 服务器数据库?

[英]How do I query SQL Server database with a user's input?

import pyodbc

def read(conn):
    print("Read")
    cursor = conn.cursor()

    userInputOpening = input("Enter a opening that you would like to know: ")
    print(userInputOpening)

    cursor.execute("select * from openings where name like '%{}%'".format(userInputOpening))
    
    for row in cursor:
        print(f"{row}")

conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=SAM-PC\SQLEXPRESS;'
                      'Database=ChessOpenings;'
                      'Trusted_Connection=yes;'
)

read(conn)

I get a error with the user input when I use an ' within the name.当我在名称中使用 ' 时,用户输入出现错误。

For example:例如:

If the userInputOpening = london如果 userInputOpening = london

It works and gives a list of all the openings that have something like "london" in them.它可以工作并列出所有包含“伦敦”之类的开口。

But...但...

If the userInputOpening = King's如果 userInputOpening = King's

It throws an error:它抛出一个错误:

cursor.execute("select * from openings where name like '%{}%'".format(userInputOpening)) pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 's'. (102) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed quotation mark after the character string ''. (105)") cursor.execute("select * from openings where name like '%{}%'".format(userInputOpening)) pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server Driver] ] 's' 附近的语法不正确。(102) (SQLExecDirectW); [42000] [Microsoft][ODBC SQL 服务器驱动程序][SQL Server]字符串 '' 后的未闭合引号。(105)")

What do I need to put in the cursor.execute() so that it takes whatever the userInputOpening entered.我需要在cursor.execute()中放入什么,以便它接受 userInputOpening 输入的任何内容。

I want to treat it like a search engine and have it display all the results of the users search.我想把它当作一个搜索引擎,让它显示用户搜索的所有结果。

I also want to make it so that user doesn't have to be perfect with their title hence why I've added the LIKE in my SQL statement我还想让用户不必完美地使用他们的标题,因此我在 SQL 语句中添加了 LIKE

Thanks!谢谢!

The problem is the quotation mark in the input string (King's) Your SQL statement then becomes问题是输入字符串中的引号(King's) 你的 SQL 语句然后变成

where name like '%King's%' 

(hence an extra single quote error message). (因此额外的单引号错误消息)。 Change the single quote to two single quotes and it should work fine将单引号更改为两个单引号,它应该可以正常工作

 userInputOpening.replace("'", "''")

Not a python guy, but I believe that is the proper replace syntax不是 python 家伙,但我相信这是正确的替换语法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM