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.
1 Answer
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)
master,model,msdbortempdb, login, and from there create your new database.Your answer is not making any sense at allon 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 theCREATE DATABASEcommand. What have you tried and what is the actual problem?