How can I pass configuration variable values into the pyodbc connect command? - python

I have a .ini (configuration file) where I have mentioned the server name, Database Name, UserName and Password with which I can connect my app to the MSSQL
self.db = pyodbc.connect(
'driver={SQL Server};server=homeserver;database=testdb;uid=home;pwd=1234')`
corresponding data mentioned above connect statement is now in config.ini
self.configwrite = ConfigParser.RawConfigParser()
configread = SafeConfigParser()
configread.read('config.ini')
driver = configread.get('DataBase Settings','Driver')
server = str(configread.get('DataBase Settings','Server'))
db = str(configread.get('DataBase Settings','Database'))
user = str(configread.get('DataBase Settings','Username'))
password = str(configread.get('DataBase Settings','Password'))'
How can I pass these variables in the pyodbc connect statement?
I tried this:
self.db = pyodbc.connect('driver={Driver};server=server;database=db;uid=user;pwd=password')
But I am getting an error.

Other options for the connect function:
# using keywords for SQL Server authentication
self.db = pyodbc.connect(driver=driver, server=server, database=db,
user=user, password=password)
# using keywords for Windows authentication
self.db = pyodbc.connect(driver=driver, server=server, database=db,
trusted_connection='yes')

self.db = pyodbc.connect('driver={%s};server=%s;database=%s;uid=%s;pwd=%s' % ( driver, server, db, user, password ) )
%s is used to include variables into the string
the variables are placed into the string according to their order after the %

Mixing strings and input variable in sql connection string using pyodbc library - Python
inspired of this answer
`conn=pyodbc.connect('Driver={SQL Server};'
'Server='+servername+';'
'Database=master;'
'UID=sa;'
'PWD='+pasword+';'
)`

Related

create new mysql database and tables using sqlalchemy

I'd like to create new database and new tables to this database using sqlalchemy. and I have to write create_engine twice, is there any easier writing method to do these things?
my code is here:
from sqlalchemy import create_engine
import pymysql
user = 'admin'
password = ''
host = 'database-1.czswegfdjhpn.us-east-1.rds.amazonaws.com'
port = 3306
engine = create_engine(url="mysql+pymysql://{0}:{1}#{2}:{3}".format(
user, password, host, port))
conn = engine.connect()
print('connect successfull')
conn.execute("commit")
conn.execute('create database covid_19')
database = 'covid_19'
engine1 = create_engine(url="mysql+pymysql://{0}:{1}#{2}:{3}/{4}".format(
user, password, host, port, database))
conn1 = engine.connect()
print('connect successfull')
df.to_sql(name="covid_19_world_cases_deaths_testing",con=engine1, if_exists='append', index=False, chunksize=200)
Haven’t tested this, however could you simply call
conn.execute(“USE covid_19”)
to change the database of the existing connection?

How to connect to external MySQL without using models.py in Django

I have my report dashboard that I'm developing using Django and I want to connect it to my MySQL database without using models.py or migrations.
Basically, here's what I've done so far.
views.py
import configparser
config = configparser.ConfigParser()
config.read('db.ini')
def getConnection():
host = config['ord']['host']
port = config['ord']['port']
database = config['ord']['database']
password = config['ord']['password']
user = config['ord']['user']
connection = pymssql.connect(host=host, user=user, password=password, database=database)
cursor = connection.cursor()
print("Connection Succesfull")
return cursor
def fill_weight(request):
try:
sql = u """
SELECT * FROM fill_weight;
"""
sql =sql.encode('utf-8')
cursor.execute(sql)
cursor.fetchall()
db.ini
[oof_ord]
host = localhost
port = 3306
database = xxxxxxxxxxx
user = xxxxxxxxxxx
password = xxxxxxxxxxx
default-character-set = utf8
The reason why I want to do this is because I don't have the official database that I'm going to use for this system and I want to easily access it by putting it's database credentials to my db.ini and access it to show the data without doing any migrations.
Is there anyone that can help me ?

Connecting to remote Oracle database using Python

I am trying to connect to a remote Oracle database using Python.
I am able to access the database directly using DBeaver and I have copied the parameters in the Python code below from the "Connection Configuration --> Connection settings --> General" tab (which can be opened by right-clicking on the database and selecting "Edit connection"):
import cx_Oracle
host_name = # content of "Host"
port_number = # content of "Port"
user_name = # content of "User name"
pwd = # content of "Password"
service_name = # content of "Database" (the "Service Name" option is selected)
dsn_tns = cx_Oracle.makedsn(host_name, port_number, service_name = service_name)
conn = cx_Oracle.connect(user = user_name, password = pwd, dsn = dsn_tns)
However, I get the following error:
DatabaseError: ORA-12541: TNS:no listener
Other answers I found related to this question suggested modifying some values inside the listener.ora file, but I have no such file on my computer nor do I know where it can be retrieved. Does anyone have any suggestions?
There would be two reason for that error.
The database was briefly unavailable at the time when you tried to access
The Oracle client application on your machine is not configured correctly
I think thi config is not correct.
See the link : https://oracle.github.io/python-cx_Oracle/
ip = '192.168.1.1'
port = 1521
SID = 'YOURSIDHERE'
dsn_tns = cx_Oracle.makedsn(ip, port, SID)
db = cx_Oracle.connect('username', 'password', dsn_tns)

Cannot connect to SQL Server from python with a specific user

I have to users to connect to a SQL Server. On the server, I need to read from SQL Server into python and write from python to SQL Server.
When I login with one one the users, everything goes fine with connection, whether I use Windows authentication or SQL Server authentication, with this code:
SQL Server authentication:
import sqlalchemy
engine = sqlalchemy.create_engine("mssql+pyodbc://myservername/mydatabasename/driver=SQL+Server+Native+Client+11.0?Trusted_Connection = no/UID = sa/PWD = mypassword")
conn = engine.connect()
df.to_sql(name = 'TestTable1', schema='dbo', con = conn)
Windows authentication:
import sqlalchemy
engine = sqlalchemy.create_engine("mssql+pyodbc://myservername/mydatabasename/driver=SQL+Server+Native+Client+11.0?Trusted_Connection = yes")
conn = engine.connect()
df.to_sql(name = 'TestTable1', schema='dbo', con = conn)
but with another user, I got this error:
Data source name too long State:IM010,Native:0,Origin:[Microsoft][ODBC Driver Manager]
Does this error do something with the other user?
For every login SQL Server needs credentials setup for Windows authentication or SQL Server authentication. You can test the credentials using SSMS before you use them in the Python program.

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`.........

Categories

Resources