Skip to content
Advertisement

pyodbc/sql – Newly created tables are going to Master database and not specified database

I am working on a project for class, where I am using Python to create a database and tables in my 2016 SQL Server. I have installed pyodbc and was able to establish a connection between Python and my SQL Server. However, when I run my code, I am able to create the ‘mydatabase’ database…but the subsequent tables that I want to create are going to the ‘Tables’ folder in the ‘Master’ database.

I have tried it both with creating the database and the tables in the same Python file, as well as only adding the tables. The result is always the same – it goes to the Master database, and not the ‘mydatabase’ database. I’ve done quite a bit of Googling, and it seems like I have the code written correctly; so, I am not sure what to look at now.

Here is the code for creating the database and tables in one fair swoop…

And here is the code for just creating the tables in the ‘mydatabase’ database, if the database already existed in SQL…

Advertisement

Answer

After the row Mycursor.execute("CREATE DATABASE mydatabase") Add mycursor.execute("USE mydatabase")

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement