Taking Input From Python To Use In Sql Query And Return Results To Screen
I have a python application where im trying to return results from a MSSQL database derived from the input entered into the python application I have already connected to the SQL
Solution 1:
Updating to account for sql injection attacks.
You need to format the string there are a few ways of doing that.
The current best practice in python is to use the new format strings. The f in front of the string lets python know that you want to format the string and {input_var}
tells python that you want to replace that with the value of the variable input_var.
defIP_Search(input_var):
cursor.execute(f"SELECT IP, Location, Description, Project, OS, DNS, NETBIOS, MAC FROM [IPAM].[dbo].[Sheet1$] WHERE IP={input_var}")
row = cursor.fetchall()
while row:
print (IP_Search)
row = cursor.fetchall()
input_var = input("Enter IP Address: ")
IP_Search(input_var)
As pointed out in the comments however this leaves the database open to SQL injection attacks. You can see details for this here: https://bobby-tables.com/python
What you do instead is pass the variables to the cursor.execute
function like this:
def IP_Search(input_var):
cursor.execute("SELECT IP, Location, Description, Project, OS, DNS, NETBIOS, MAC FROM [IPAM].[dbo].[Sheet1$] WHERE IP=%s", (input_var,))
row = cursor.fetchall()
while row:
print (IP_Search)
row = cursor.fetchall()
input_var = input("Enter IP Address: ")
IP_Search(input_var)
Post a Comment for "Taking Input From Python To Use In Sql Query And Return Results To Screen"