0

I am using the following code to extract data from SQL into a Data Frame and it works fine.

import pyodbc 
cnxn = pyodbc.connect("Driver={SQL Server Native Client 11.0};"
                      "Server=DESKTOP-5422GFU;"
                      "Database=Python_Data;"
                      "Trusted_Connection=yes;"
                      "uid=User;pwd=password")

df = pd.read_sql_query('select * from Persons', cnxn)

df

But when I add this line

df.to_sql('test', schema = 'public', con = cnxn, index = False, 
if_exists = 'replace')

to send data back to the Server I get an error that says

DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': ('42S02', "[42S02] [Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid object name 'sqlite_master'. (208) (SQLExecDirectW); [42S02] [Microsoft][SQL Server Native Client 11.0][SQL Server]Statement(s) could not be prepared. (8180)")

I have tried a variety of solutions and just can't get it to work.

Azsgy
  • 3,139
  • 2
  • 29
  • 40
Shawn
  • 1
  • 3
  • Possible duplicate of [Writing python (pandas) Data Frame to SQL Database Error](https://stackoverflow.com/questions/26055556/writing-python-pandas-data-frame-to-sql-database-error) – Nickolay Sep 03 '18 at 13:22

1 Answers1

-1

I believe the issue is in your "con = cnxn" statement. Try this:

import pandas as pd    
import sqlalchemy
from sqlalchemy import create_engine

OBDC_cnxn='Python_Data_ODBC' #this will be the name of the ODBC connection to this database in your ODBC manager.
engine = create_engine('mssql+pyodbc://'+ODBC_cnxn)

df.to_sql('test', schema = 'public', con = engine, index = False, 
if_exists = 'replace')
Samsonite Manly
  • 569
  • 2
  • 7
  • 15