In my code I am opening two mysql connections and using HTTP requests to insert data into database
g.db = mysql.connector.connect(user=a ,password=password, host=localhost,database=mysq1)
g.db1 = mysql.connector.connect(user=b,password=password, host=localhost,database=mysql2)
@app.route('/user/<db>')
def insert(db):
#code for inserting data into mysql1 database
#code for inserting data into mysql2 database
I am making HTTP requests to select the databases.
curl -i 'localhost:5000/user/mysql1' #
It is working well, data is getting inserted into the selected database. But I was thinking of creating a connection pool for the two connections and then used that pool.
Questions:
How to implement the mysql connection pooling?
Is there other better way of initializing connections.Currently connection get opened at each request.
You could create a connection pool at the beginning with
create_pool()
which finally causeMySQLConnectionPool()
, and when you need to connect to MySQL, you could get a connection withget_connection()
from the pool, and when you do not need the connection you could add the connection back to the pool withconn.close()
.Use ORM frameworks for making things easier, below is a basic and a general way we create a connection pool with out any ORM frameworks.
Create your own pool and name it, myPool in the arguments of connection pooling, you can also declare the pool size = 5 (which is the number of database connections).
Please see below for more information:
dbconfig, database configuration is where you give all the configuration details, everytime you change your databse. In fact you can have multiple databases, if you want to.
Please see this MySQL documentation here
We can see more about how this arguments can be declared:
This constructor instantiates an object that manages a connection pool.
Arguments in detail:
You should see this some nice documentation here
For making your connection pool multithreaded, this post on stackoverflw might really help. Please see this post
Another way would be using any Web Server, I suggest you to use JBoss. You can create a datasource and configure it with the number of connections that you want to be controlled and let it be controlled by JBoss.