0

I need to connect to the ms-sql database and then create a new database there using python script. I have the user credentials for the login. So how to create the connection to the ms-sql server using python.

3
  • 1
    Your answer is not making any sense at all as 1. I don't want to connect to a default database but create new as needed as soon as login. 2. If possible please reply with appropriate code and proper explanation. Commented Sep 29, 2022 at 9:00
  • One SQL Server can host multiple databases. Since you can't reference a database that doesn't exist in your connection string (that's a login error) you specify a database that already exists (and you have access to) in your connection string such as master, model, msdb or tempdb, login, and from there create your new database. Commented Sep 29, 2022 at 9:03
  • @ArunYadav Your answer is not making any sense at all on the contrary, it's the question that's unclear, which is why it's getting downvoted and close-voted. If you don't want to specify a database in the connection, just don't. If you want to create a new one, use the CREATE DATABASE command. What have you tried and what is the actual problem? Commented Sep 29, 2022 at 9:11

1 Answer 1

3

If you do not have database name then use the connection string as mentioned in the code below. Create a database after connection and use the database finally.

import pyodbc

# if you have user id and password then try with this connection string
connection_string = f"DRIVER={SQL Server};SERVER={server_name};UID={user_id};PWD={password}"

# if using in the local system then use the following connection string
connection_string = f"DRIVER={SQL Server};SERVER={server_name}; Trusted_Connection=True;"

connection= pyodbc.connect(connection_string)
cursor = connection.cursor()

sql_create_database = f"CREATE DATABASE {database_name}"
cursor.execute(sql_create_database)

set_database = f"USE {database_name}"
cursor.execute(set_database)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.