简体   繁体   中英

SQLAlchemy to connect to MSSQL using instance name

Ok so here is my use case. I've to make connection to different types of DB(MSSQL, oracl, MYSQL, etc.). I've .sql files for each of these database. As it seems sqlalchemy can't run .sql file so we need to open and execute the statements one by one from the .sql files over the connection.

So guys, I'm having this information and I wanted to connect using SQL Alchemy.

<db type="MSSQL" version="2005" patch_level="SP2" port="1433" id="MSSQLSERVER"/>

here MSSQLServer is the instance. No DB information is provide. so do I need DB name to connect to DB?

this is my command

engine = create_engine('mssql+pyodbc://sa:pass@172.21.153.227/MSSQLSERVER', echo=True)

this is my complete code

from sqlalchemy.engine import create_engine
engine = create_engine('mssql+pyodbc://sa:pass@172.21.153.227', echo=False)
connection = engine.connect()
connection.execute(
    """
    select @@version
    """
)
connection.close()

you don't need a db name, you can use this function i wrote: (it works for me on mySQL)

def ConnectToDB(self, server, uid, password):
        """
        this method if for connecting to a db
        @param server: server name
        @param uid: username
        @param password: password
        """

        connection_string = 'mysql://{}:{}@{}'.format(uid, password, server)

        try:
            self.engine = create_engine(connection_string)
            self.connection = self.engine.connect()
        except exc.SQLAlchemyError, e:
            self.engine = None
            return False, e

        return True, None

in your SQL statements you will say the DB and table some thing like this:

INSERT INTO `dbName`.`dbTable`.........

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