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!
Related
I'm making a Flask application that is using sqlalchemy as a layer between the application and a postgres database. Currently I'm using a 'config.py' file that fetches the sensible connection info from system variables. But my IT admin says it's not sufficiently safe as we will be hosting the server ourselves rather than using PAAS. What would be the most smooth and efficient way to provide the db connetion to sqalchemy without exposing the sensitive connection info to anybody that have access to the server (and thereby being able to read the system variables)?
I'm using VisualStudio as IDE, so dev environment is windows, but would like to be able to deploy on linux if needed.
This is my 'runserver.py' file:
...
from config import DevelopmentConfig, ProductionConfig, TestingConfig
app = create_app(ProductionConfig)
if __name__ == '__main__':
HOST = environ.get('SERVER_HOST', 'localhost')
try:
PORT = int(environ.get('SERVER_PORT', '6388'))
except ValueError:
PORT = 6388
app.run(HOST, PORT)
And this is my '__init__.py' file:
def create_app(config=DevelopmentConfig):
app = Flask(__name__)
app.config.from_object(config)
db.init_app(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.
I'm developing a web app, and I need to know how to configure a SQLite database.
I used db = SQL("sqlite:///database.db") where SQL is a private function from school. I can't access the definition, how would I do this?
Why not simply use sqlite3 package from python standard library ?
import sqlite3
conn = sqlite3.connect('mydb.db')
Here's the link for python 3.7 : https://docs.python.org/3.7/library/sqlite3.html
I have SQLAlchemy CORE 1.0.9 with Pyramid framework 1.7. And I am using the following configuration for connecting to a postgres 9.4 database:
# file __ini__.py
from .factories import root_factory
from pyramid.config import Configurator
from sqlalchemy import engine_from_config
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application."""
config = Configurator(settings=settings, root_factory=root_factory)
engine = engine_from_config(settings, prefix='sqlalchemy.')
# Retrieves database connection
def get_db(request):
connection = engine.connect()
def disconnect(request):
connection.close()
request.add_finished_callback(disconnect)
return connection
config.add_request_method(get_db, 'db', reify=True)
config.scan()
return config.make_wsgi_app()
After a few hours using the app I start getting the following error:
sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) FATAL: remaining connection slots are reserved for non-replication superuser connections
Apparently I have reached the maximum number of connections. It seems like connections.close() doesn't really close the connection, just returns the connection to the pool. I know I could use the NullPool to disable pooling but probably that will have a huge impact in the performance.
Does somebody know the right way to configure SQLAlchemy Core to get a good performance and close the connections properly?
Please abstain from sending links to pyramid tutorials. I am NOT interested in SQLAlchemy ORM setups. Only SQLAlchemy Core please.
Actually everything was fine in the previous setup. The problem was caused by Celery workers not closing connections.
I want to know if it's possible to connect to the database is use
when i use PHP, in Visual Studio.
I have the database hosted on a VPS server and wounder if(and how)
i could connect my vb.net application to it.
And i also want to know how to get data from the database.
I use Visual Studio 2010. I have VS 2012 and can use it if i need to.
I've tried to do it in the Server Explorer, and clicked "Connect to database".
But i don't know if that's right and i don't know where and what to write.
I know the mySql details, but not where to write them.
Yes you can, Please follow this steps :
1.You need to download the mysqlconnect (mysql-connector-net) from the MySQL website and add the DLL files to Visual Studio, the website is http://dev.mysql.com/downloads/connector/. Extract the download file.
Add a reference to the MySql assembly. Click the Project from the menu and then select Add Reference. Under the .Net tab, browse for the MySQL.Data assembly.
On your class add this tow imports lines :
Imports System.Data
Imports MySql.Data.MySqlClient
To connect to the MySql database, we need to use the MySqlConnection Class :
Dim con = New MySqlConnection("Data Source=localhost;user id=root;database=my_test_projects;")
Use it like this :
Try
con.Open()
'Check if the connection is open
If con.State = ConnectionState.Open Then
con.ChangeDatabase("MYSQL") 'Use the MYSQL database for this example
Console.WriteLine("Connection Open")
Dim Sql As String = "SELECT * FROM USER" ' Query the USER table to get user information
cmd = New MySqlCommand(Sql, con)
reader = cmd.ExecuteReader()
End If
Catch ex As Exception
Console.WriteLine(ex.Message) ' Display any errors.
End Try
See This link Using MySQL Database with Visual Basic .NET 2010