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.

jarlh
  • 42,561
  • 8
  • 45
  • 63
Arun Yadav
  • 33
  • 4
  • 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. – Arun Yadav Sep 29 '22 at 09: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. – AlwaysLearning Sep 29 '22 at 09: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? – Panagiotis Kanavos Sep 29 '22 at 09:11

1 Answers1

1

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)