error mysql

MySQL Error 1049 - Unknown Database

Understanding MySQL error 1049 - the specified database does not exist on the MySQL server.

What It Means

MySQL error 1049 (ER_BAD_DB_ERROR) means “Unknown database ‘database_name’.” The database you are trying to connect to or use does not exist on the MySQL server. This can happen when connecting or when running USE database_name.

Common Causes

  • Typo in the database name
  • Database has not been created yet
  • Database was dropped or deleted
  • Case-sensitivity mismatch (MySQL on Linux is case-sensitive for database names)
  • Environment variable pointing to wrong database name
  • Migration or setup script hasn’t run yet

How to Fix

Check existing databases

# List all databases
mysql -u root -p -e "SHOW DATABASES;"

# Check if the name is case-sensitive
mysql -u root -p -e "SHOW DATABASES LIKE '%mydb%';"

Create the database

-- Create the database
CREATE DATABASE mydb CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- Grant access
GRANT ALL PRIVILEGES ON mydb.* TO 'myapp'@'localhost';
FLUSH PRIVILEGES;

-- Verify
SHOW DATABASES;

Fix application configuration

// Node.js - check your connection config
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'myapp',
  password: 'password',
  database: 'mydb'  // Make sure this matches exactly
});
# Python - verify database name
import mysql.connector

connection = mysql.connector.connect(
    host='localhost',
    user='myapp',
    password='password',
    database='mydb'  # Case-sensitive on Linux
)

Auto-create in Docker

# Docker Compose - database is created automatically
services:
  db:
    image: mysql:8.0
    environment:
      MYSQL_ROOT_PASSWORD: rootpass
      MYSQL_DATABASE: mydb        # Created on first start
      MYSQL_USER: myapp
      MYSQL_PASSWORD: apppass
    volumes:
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql  # Extra init scripts

Create programmatically

// Node.js - create database if it doesn't exist
const mysql = require('mysql2/promise');

async function ensureDatabase() {
  const connection = await mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'rootpass'
    // Don't specify database here
  });

  await connection.query('CREATE DATABASE IF NOT EXISTS mydb');
  await connection.end();
}
# Python
import mysql.connector

conn = mysql.connector.connect(host='localhost', user='root', password='rootpass')
cursor = conn.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS mydb")
conn.close()
  • MySQL 1045 - Access denied: Authentication failed before reaching the database.
  • MySQL 1146 - Table doesn’t exist: Connected to the database but a table is missing.
  • MySQL 2003 - Can’t connect: Cannot reach the MySQL server at all.