简体   繁体   中英

“Invalid object name” error when executing query using sqlalchemy

I connect database with pycharm and I use sqlAlchemy. When I am trying to execute an insert query it shows the following error:

Invalid object name 'pfAnalytics.optPrice'

The error is due to the fact that it add "[" and "]" to my tables' name when I do :

ins = table.insert()

if I check the string I see:

str(ins) == 'INSERT INTO [pfAnalytics.optPrice] DEFAULT VALUES'

instead of:

str(ins) == 'INSERT INTO pfAnalytics.optPrice DEFAULT VALUES'

my request look like this:

listToWrite = all.to_dict(orient='records')

metadata = sql.schema.MetaData(bind=engine,reflect=True)
table = sql.Table("pfAnalytics.optPrice", metadata)

Session = sessionmaker(bind=engine)
session = Session()

querydel = sql.delete("pfAnalytics.optPrice")
results = consql.execute(querydel)

consql.execute(sql.insert(table), listToWrite)

How to get rid of these brackets?

The answer is tricky, it iss du to an error on SQL server. So I had to specify to to put no bracket at the begining and the end of the table's name with :

engine.dialect.identifier_preparer.initial_quote = ''
engine.dialect.identifier_preparer.final_quote = ''

I ran into this issue using MSSQL Server and could not seem to find an answer that would work for me. I finally discovered the problem to be in connection string for the db engine. Apparently SQLAlchemy needs the driver included in the string. This holds true if you are using a Flask app, for the URI as well as creating an engine.

An example in the Flask app:

app.config["SQLALCHEMY_DATABASE_URI"] = "mssql+pyodbc://username:\
password@server/database?driver=SQL+Server"

Similarly, in creating an engine:

db_string = "mssql+pyodbc://username:password@server/database?driver=SQL+Server"
engine = create_engine(db_string)

It seems that driver=SQL+Server is the key to making this work for me. I didn't see this on the official documentation but noticed it in another post on Stack Overflow. So credit to Praveen for this:

Connect to MSSQL Database using Flask-SQLAlchemy

The exact error I was getting from SQLAlchemy/pyodbc was:

sqlalchemy.exc.ProgrammingError: (pyodbc.ProgrammingError) ('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 

Hopefully this can save someone the headache it created for me.

In my case I had to use Database instead of Initial Catalog .
Compare these two, to get the difference:

  • not working one:
Server=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
  • working one:
Server=myServerAddress;Database=myDataBase;UID=myUsername;PWD=myPassword;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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