Creating MySQL databases programmatically in Node.js requires initializing an administrative connection to the database server, issuing CREATE DATABASE Data Definition Language (DDL) queries, and specifying appropriate character sets.
flowchart LR
A["Node.js Application"] -->|"mysql.createConnection(host, user, pass)"| B["MySQL Server Host"]
B -->|"CREATE DATABASE IF NOT EXISTS app_db CHARACTER SET utf8mb4"| C["New MySQL Schema Initialized"]
import mysql from 'mysql2/promise';
async function initializeDatabaseSchema() {
// Initial connection without specifying target database name
const adminConnection = await mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'rootpassword'
});
const targetDbName = 'kodersolution_dev';
try {
console.log(`Creating database schema '${targetDbName}'...`);
// Execute DDL query specifying utf8mb4 encoding for full emoji support
const query = `
CREATE DATABASE IF NOT EXISTS \`${targetDbName}\`
CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;
`;
await adminConnection.query(query);
console.log(`Database '${targetDbName}' created or already exists.`);
} catch (error) {
console.error('Database Creation Error:', error.message);
} finally {
await adminConnection.end();
}
}
initializeDatabaseSchema();
IF NOT EXISTS: Always add IF NOT EXISTS to DDL queries to avoid process errors if the target database already exists.utf8mb4 Encoding: Always use utf8mb4 encoding instead of standard utf8 in MySQL to support 4-byte Unicode characters (such as emojis).`db_name`) when interpolating database names into raw DDL SQL.Why is utf8mb4 preferred over utf8 in MySQL database character set configuration?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With