Search code examples
sql-serverpython-3.xpypyodbc

Incorrect syntax near Go with Pypyodbc


I am using the pypyodbc library to establish a connection to a SQL Server 2008 R2 database and every time I try to execute a .sql file I encounter the following error:

pypyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 'Go'.")

This is the sql query I am trying to execute:

Use SL_Site1_App
Go

select emp_num,name, trans_num, job, trans_type
from Hours where trans_type like '1000%'  order by trans_date desc

This is the python script that I am using:

import pypyodbc, ExcelFile

def main():
    # read the SQL queries externally
    queries = ['C:\\Temp\\Ready_to_use_queries\\Connection_sql_python.sql']

    for index, query in enumerate(queries):
        cursor = initiate_connection_db()
        results = retrieve_results_query(cursor, query)
        if index == 0:
            ExcelFile.write_to_workbook(results)
            print("The workbook has been created and data has been inserted.\n")

def initiate_connection_db():      
    connection_live_db = pypyodbc.connect(driver="{SQL Server}", server="xxx.xxx.xxx.xxx", uid="my-name",
                                      pwd="try-and-guess", Trusted_Connection="No")
    connection = connection_live_db.cursor()
    return connection

The workaround for this problem is to delete the Use SL_Site1_App Go line but I want to know if this is a known problem related to the pypyodbc library to process these lines and if so, where should I look to notify the developers about this issue.


Solution

  • GO is a batch separator used by sqlcmd and SSMS. It's not a T-SQL operator.

    Considering you're using an application to connect to SQL Server, declare your database in the connection string, by adding database="SL_Site1_App", and then remove the USE and GO statements in your SQL Statement.