In Python use PyMySQL (or mysql-connector-python); in Node.js use mysql2. In both the host is localhost, the database and user names carry the account prefix, and the password goes in an environment variable, not in the code. The application runs through the «Setup Python App» and «Setup Node.js App» tools in cPanel.
Python
| 2 |
In Setup Python App, open your application. At the top is the command that enters the virtual environment. Run it in the Terminal and install the library: pip install pymysql. See virtual environments and pip.
|
|
| 3 |
In the code:import os, pymysql link = pymysql.connect(host='localhost', user=os.environ['DB_USER'], password=os.environ['DB_PASS'], database=os.environ['DB_NAME'], charset='utf8mb4') with link.cursor() as cur: cur.execute('SELECT NOW()') print(cur.fetchone())
|
|
| 4 |
Set DB_USER, DB_PASS and DB_NAME in the application’s own environment variables in cPanel, and restart it.
|
|
Node.js
| 2 |
In the code:const mysql = require('mysql2/promise'); const pool = mysql.createPool({host: 'localhost', user: process.env.DB_USER, password: process.env.DB_PASS, database: process.env.DB_NAME, charset: 'utf8mb4'}); const [rows] = await pool.query('SELECT NOW() AS now_time');
|
|
| 3 |
Use a pool and not a new connection on every request. Environment variables are set on the application’s page, just as in Python.
|
|
| Symptom |
Likely cause |
| Access denied for user |
Name without the account prefix, wrong password, or user not linked to the database. |
| Can’t connect to MySQL server on ‘localhost’ |
The application tried a network address instead of localhost. Do not use the server IP. |
| Too many connections |
The application opens connections and never closes them. See the max_user_connections error. |
| Server has gone away |
A connection left idle for a long time and then reused. See the causes, in order. |
Reusing connections
In both languages, opening a connection is the expensive part. On a site with visitors, a new connection on every request uses up the available connections and slows everything down. In Python keep one connection per application process, or use a pool (SQLAlchemy ships one). In Node create the pool once, at start-up, and use pool.query on each request. And remember: after changing the code or the environment variables, restart the application in the cPanel tool itself, or it keeps running the old version.
PostgreSQL instead of MySQL? In Python swap the library for psycopg2-binary, in Node for pg, and the port becomes 5432. The pool logic is the same.
|
|
The application starts but never reaches the database? Tell us which tool it is (Python or Node) and the exact error and we will look.
Open a support ticket
|
RECOMMENDED PRODUCT Web hosting with cPanel Domain and SSL included, daily backups and the panel you already know. from $6.60/mo (3-year plan, with coupon) See plans |