1
votes

I am using Pyodbc, and am connected to a database. I can easily pull out data where I am just using the SELECT and FROM statements.

However when I try to use a WHERE statement it is throwing syntax errors:

This is the code:

import pyodbc

conn = pyodbc.connect('DSN=QueryBuilder')
cursor = conn.cursor()
cursor.execute('SELECT * FROM dbo.Grantinformation WHERE HoldingOrganisationName = 'university of edinburgh'')

I get this error:

SyntaxError: invalid syntax

If i run:

SELECT * 
FROM dbo.Grantinformation
WHERE HoldingOrganisationName = 'university of edinburgh'

in SQL Server Management Studio the SQL runs fine, so it is obviously something that I am doing wrong with pyodbc?

Many thanks

1

1 Answers

6
votes

No, this is a simple Python syntax error. You have single quotes inside your sql string, so you need to use double quotes around the string itself:

cursor.execute("SELECT * FROM dbo.Grantinformation WHERE HoldingOrganisationName = 'university of edinburgh'")