SQL Alchemy and cx_oracle - Can ONLY connect to system - sqlalchemy

trying to learn how to work with SQLalchemy and Oracle.
In my below code, I can connect to system just fine, but when I try to connect to the sample DB called 'HR", I get an error:
import sqlalchemy as db
from sqlalchemy import create_engine
from sqlalchemy import MetaData
from sqlalchemy.ext.declarative import as_declarative
engine = db.create_engine("oracle://hr:oracle#localhost:1521/orclcdb")
connection = engine.connect()
metadata = MetaData(engine)
metadata.reflect()
dept = db.Table('EMP',metadata,autoload=True,autoload_with=engine)
query = db.select([dept])
result_proxy=connection.execute(query)
result_set = result_proxy.fetchall()
print(result_set[0])
print(result_set[:2])
sqlalchemy.exc.DatabaseError: (cx_Oracle.DatabaseError) ORA-01017: invalid username/password; logon denied
(Background on this error at: https://sqlalche.me/e/14/4xp6)
Also, when I do connect with system, I can't retrieve the EMP table:
import sqlalchemy as db
from sqlalchemy import create_engine
from sqlalchemy import MetaData
from sqlalchemy.ext.declarative import as_declarative
engine = db.create_engine("oracle://system:oracle#localhost:1521/orclcdb")
connection = engine.connect()
metadata = MetaData(engine)
metadata.reflect()
dept = db.Table('EMP',metadata,autoload=True,autoload_with=engine)
query = db.select([dept])
result_proxy=connection.execute(query)
result_set = result_proxy.fetchall()
print(result_set[0])
print(result_set[:2])
File "/home/oracle/code/sqlalchemy-workspace/lib64/python3.6/site-packages/sqlalchemy/engine/reflection.py", line 789, in reflect_table
raise exc.NoSuchTableError(table_name)
sqlalchemy.exc.NoSuchTableError: EMP
Also added a screenshot of my connection to system via SQL Dev.
Also, I noticed that it is really slow, takes almost 10 seconds to get the error back.
Without SQLalchemy it is instant and I can connect to any user I have set up just fine.
I hope you can help me make sense of all that. Thank you.
System info:
Using an Oracle Appliance 19, which is on Oracle Linux 7. (VirtualBox)
Using VScode with remote ssh, python 3.8.
SQLalchemy is in a python venv.

Related

How to connect database with FastAPI app?

I have mysql server on python anywhere platform. I have a FastAPI app. I would like to access to my database from my FastAPI app. I know that I can reach the database directly from FastAPI app and I saw many tutorials but I am finding the set up a bit complicated and as a beginner I would like to keep it simple.
From pythonanywhere platform support I know I can reach my database from python script with ssh tunneling. I have tested the solution and it worked well.
If I hash my password not as it is in the following script, do you believe this is a suitable solution ?
This is database.py
#database.py
import MySQLdb
import sshtunnel
sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0
def get_data():
with sshtunnel.SSHTunnelForwarder(
('ssh.pythonanywhere.com'),
ssh_username='username', ssh_password='hashed',
remote_bind_address=('username.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
connection = MySQLdb.connect(
user='username',
passwd='hashed',
host='127.0.0.1', port=tunnel.local_bind_port,
db='username$dbName',
)
# Do stuff
with connection as con:
with con.cursor() as c:
c.execute("SELECT * FROM table;")
res = c.fetchall()
return res
This is the fastapi app script main.py
#main.py
from fastapi import FastAPI
from database import get_data
app = FastAPI()
#app.get('/mesures')
def get_mesures():
return get_data()
Again, I know this is not best solution but just would like your thoughts.
Ok I close this post as answered based on replies in comment.
Assuming that the FastAPI app is hosted somewhere else, SSH tunneling is the only option to connect to your PA-hosted MySQL db. You need a paid account in order for that to work
Currently FastAPI web apps would not work on PythonAnywhere, but we're working on this -- once it's ready, I guess you will be able to host the web app on PA and connect it with your db in a less "hacky" way. For now tunneling is the only option.

sqlalchemy.dialects: "synapse." pyodbc

Please let me know how to connect to azure synapse with sql alchemy create_engine().
I tried using the connection string same as mssql. But it throws error.
I am able to connect with pyodbc.
import pyodbc
pyodbc.connect(driver='ODBC Driver 17 for SQL Server',
server=server,
port=1433,
database=database,
uid=user_name,
pwd=password,
autocommit=True)
But below code doesn't work:
import sqlalchemy.create_engine
engine = create_engine(
"synapse+pyodbc://scott:tiger#synapse.sql:1433/test?driver=ODBC+Driver+17+for+SQL+Server",
fast_executemany=True)
Im getting sqlalchemy.dialects: "synapse." pyodbc error.
Any help would be appreciated.

IronPython: How do I connect to a MySQL Database?

I have a DigitalOcean droplet running a MySQL server working perfectly well. I am trying to connect to this server via a IronPython desktop app in Visual Studio.
Here is my code for connecting to the database:
import wpf
import clr
clr.AddReference('System.Data')
from System.Data import DataSet
from System.Data.Odbc import OdbcConnection, OdbcDataAdapter
from System.Windows import Application, Window
class MyWindow(Window):
def __init__(self):
wpf.LoadComponent(self, 'Vulpes.xaml')
connectString = "Server=***.***.***.***;Database=****;Uid=root;Password=****"
query = "SELECT * FROM users"
connection = OdbcConnection(connectString)
adaptor = OdbcDataAdapter(query, connection)
dataSet = DataSet()
connection.Open()
adaptor.Fill(dataSet)
connection.Close()
if __name__ == '__main__':
Application().Run(MyWindow())
The issue here is with the connection.Open() and connection.Close(functions), if I comment out those parts, everything works great. The username, server address, password, and DB name are all correct and the query is a valid query.
I'm thinking my method is just outdated, and while I'd love to do something more modern, IronPython only supports a very limited amount of Python modules, and so I'm having trouble finding another way to do it this way. There's not even a list of all the supported modules in their documentation, so you just have to look through MySQL modules and do trial-and-error.
If anyone has a better way of connecting to a MySQL DB via IronPython, I would love to hear it.
Thanks for your time!

cant connect to MySQL on aws RDS with flask-sqlalchemy

I am trying to connect to an RDS instance with flask-sqlalchemy. But i cant get it to work. I am getting the error
sqlalchemy.exc.OperationalError: (MySQLdb._exceptions.OperationalError) (1049, "Unknown database 'dbname'")ยจ
My database URI looks like this
SQLALCHEMY_DATABASE_URI = 'mysql://username:password#dbname.xxxxxxxxxxxx.eu-central-1.rds.amazonaws.com:3306/dbname'
I have tried using the pymysql plugin, but it didnt make any difference.
I think my security groups are setup correctly.
On the RDS instance it is this
(I dont know if security groups contain any personnel info)
Try creating the database first:
import pandas as pd
import sqlalchemy
mysql_engine = sqlalchemy.create_engine("mysql://username:password#dbname.xxxxxxxxxxxx.eu-central-1.rds.amazonaws.com:3306")
pd.read_sql_query("create database dbname", con=mysql_engine)

peewee: ImproperlyConfigured error

I'm trying to run my application with peewee on a server and it keeps crashing.
To start the application the start function is called in main.py:
def start(db_name, db_user, db_pass):
BaseModel.initialize_database(db_name, db_user, db_pass)
classA.create_table()
classB.create_table()
return app
It crashes on the first line in the BaseModel class.
from peewee import MySQLDatabase
from peewee import Model
I get the following error: "ImproperlyConfigured: Either sqlite3, psycopg2 or MySQLdb must be installed".
I don't understand the error because the database is running on the same server. The database was created using phpmyadmin.
When I test the application on my laptop everything works fine, for testing I use an SQLite database "test.db".
Peewee was unable to import any of the known database drivers. Try running this from your interactive shell:
import sqlite3
import psycopg2
import MySQLdb
If they all fail with an import error, then that would explain your issue.
In Pycharm:
click File
click settings
on Project interpreter tap , select install button (Plus shape)
Search on mysql and install it
search on mysql-connector and install it