Error 1049 42000 unknown database root

I can't seem to login to my tutorial database development environment: Ayman$ mysql -u blog -p blog_development Enter password: ERROR 1049 (42000): Unknown database 'blog_development' I can log...

I can’t seem to login to my tutorial database development environment:

Ayman$ mysql -u blog -p blog_development
Enter password: 
ERROR 1049 (42000): Unknown database 'blog_development'

I can login to the database fine without the blog_development portion:

Ayman$ mysql -u blog -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 1858

Not sure what gives as I granted all access:

mysql> GRANT ALL PRIVILEGES ON blog_development.*
    -> TO 'blog'@'localhost'
    -> IDENTIFIED BY 'newpassword';
Query OK, 0 rows affected (0.01 sec)

mysql> SHOW GRANTS FOR 'blog'@'localhost'
    -> ;
+----------------------------------------------------------------------------------------- --------------------+
 | Grants for blog@localhost                                                                                        |
 +----------------------------------------------------------------------------------------- --------------------+
| GRANT USAGE ON *.* TO 'blog'@'localhost' IDENTIFIED BY PASSWORD    '*FE4F2D624C07AAEBB979DA5C980D0250C37D8F63' |
| GRANT ALL PRIVILEGES ON `blog`.* TO 'blog'@'localhost'                                                        |
| GRANT ALL PRIVILEGES ON `blog_development`.* TO 'blog'@'localhost'                                           |
+----------------------------------------------------------------------------------------- --------------------+
3 rows in set (0.00 sec)

Anybody have a clue what to try? Thanks! Also, side note- is it weird I have multiple root users?:

mysql> select User from mysql.user;
+------+
| User |
+------+
| root |
| root |
|      |
| root |
|      |
| blog |
| root |
+------+
7 rows in set (0.00 sec)

Edit: for those asking- I created the database blog with the CREATE DATABASE command in MySql. Here are my active databases:

mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+  
| information_schema |
| blog               |
| mysql              |
| performance_schema |
| test               |
+--------------------+ 
5 rows in set (0.00 sec)

This document (7009762) is provided subject to the disclaimer at the end of this document.

Environment

SUSE Linux Enterprise Server 10 Service Pack 1

SUSE Linux Enterprise Server 10 Service Pack 2

SUSE Linux Enterprise Server 10 Service Pack 3

SUSE Linux Enterprise Server 10 Service Pack 4

SUSE Linux Enterprise Server 11 Service Pack 1

SUSE Linux Enterprise Server 11 Service Pack 2

Situation

ERROR 1049 (42000): Unknown database ‘mysql’ when trying to access mysql via this command:

this command will access the default ‘mysql’ database, and needs to be done prior to setting or resetting the root users’ MySQL password.

Resolution

Depending on how MySQL was installed, it is possible that the default MySQL database was NOT created. 

This may be checked by looking in /var/lib/mysql for a mysql subfolder (i.e. /var/lib/mysql/mysql ). If the path does NOT contain a mysql subfolder, it needs to be created by completing the following steps:
 

rcmysql stop
pkill mysql   (NOTE: wait until notification is given that mysqld ended, then hit <ENTER>)
/usr/bin/mysql_install_db

Now that the above steps have been run, check and make sure that the database was created:
 

cd /var/lib/mysql
ls -al | grep mysql

In the listing output there should now be a folder called mysql.  Finally, the correct owner and group need to be set on the mysql folder.

Restart the mysql service in safe mode again and attempt the initial command again:

Disclaimer

This Support Knowledgebase provides a valuable tool for SUSE customers and parties interested in our products and solutions to acquire information, ideas and learn from one another. Materials are provided for informational, personal or non-commercial use within your organization and are presented «AS IS» WITHOUT WARRANTY OF ANY KIND.

  • Document ID:7009762
  • Creation Date:
    17-Nov-2011
  • Modified Date:12-Aug-2022
    • SUSE Linux Enterprise Server

< Back to Support Search

For questions or concerns with the SUSE Knowledgebase please contact: tidfeedback[at]suse.com

Mysqldump is a tool frequently used in creating a backup of a mariadb or mysql database. To use this tool is pretty straight forward, just run below command:

$ mysqldump -u root -p mydatabasename > mydatabasename.sql 

The above command is fine, and we can always restore the data from the sql file into a database provided we have the database already in place, using below command:

$ mysql -u root -p mydatabasename <  mydatabasename.sql

A problem appears when we are transferring the sql file to another server which does not have the database already created. If we try to import the sql file, without the database already existed, we will get below error:

ERROR 1049 (42000): Unknown database mydatabasename

We can prevent this by adding an option to our mysqldump command. The option is «—databases» or in short «-B». To test it out, we can use below commands (dump the db, drop the db, and import back the db from the sql file):

$ mysqldump -u root -p —databases mydatabasename > mydatabasename.sql

$ mysqladmin -u root -p drop mydatabasename

$ mysql -u root -p < mydatabasename.sql     

This time, you would not get the above error, since the «—databases» option will add «CREATE DATABASE» query into the sql file, and that query will create the database if the database is not already exist.

In fact, I made a very serious mistake, and this mistake can only be reported for two reasons.
Reason 1: There is an extra space after your account password, which means you have the wrong database.
Fix: If it is a login password, report this error, as shown in the figure below:

It would be possible to have an extra space between p and 123, and then you would remove the space in between. You put p and 123 together and you type in p123
Reason 2: Your syntax is wrong, because use can only be followed by the database name, never the table name. An incorrect or incorrect table name will report the following error.

Solution: Double check your database to see if it has TB_EMP6.

Check your table again to see if it is your table name.

The name of the table is confused with the database name.
Summary is to confirm the database name is not exist, there are no spelling mistakes, if not again to see your grammar is not wrong.
This is better to locate your problem, in fact, to put it bluntly this is I made a stupid mistake, but also eat a catty gain a wisdom.
Hope to help you, welcome to leave a message to exchange ~

Read More:

Often while performing WHM backups, users notice an error “mysqldump: Got error: 1049: Unknown database”. This can happen when the database does not exist in MySQL.

As a part of our Server Management Services, we help our customers with similar requests related to WHM/ cPanel.

Let us today, discuss the possible reasons and fixes for this error.

What causes “MySQLdump: got error :1049 :unknown database ” error

MySQLdump helps to perform the logical backups, generating a set of SQL statements like DDL, DML for reproduced backup Schema. It dumps one or more MySQL databases for backup or transfers to another SQL server.

We can also generate output in CSV, other delimited text or XML format. The main drawback of MySQLdump is that the restoration procedure can take a long time to execute if the database is very large.

While performing WHM backups, at times, we can see the following error in the backup log:

The backup process encountered the following error: The backup process on “hostname.example.server” encountered an error.
[2021-05-10 02:25:26 -0600] mysqldump: Got error: 1049: Unknown database ‘example_database’ when selecting the database

Generally, This error indicates that the related database exists in a cPanel user’s database map, but the database does not exist in MySQL.
 

How to fix “MySQLdump: got error :1049 :unknown database ” error

The first thing that our Support Engineers perform on seeing this error is to check whether the database exists within MySQL. They does this by running the following command as the root user via SSH:

mysql -e "show databases;" | grep example_database

Replace example_database with the database found within the backup error in the backup logs. We can find the backup logs within /usr/local/cpanel/logs/cpbackup.

If the above command does not display any results, it indicates that the database does not exist in MySQL.

Thus, In order to correct the backup errors, we have to remove the databases that do not actually exist in MySQL from cPanel.

For this, we initially log in to the cPanel account for the particular database user. Then, we navigate to the Databases section and then click on the MySQL Databases option.

Here, we just need to delete the corresponding database from the current database section.

mysqldump got error 1049 unknown database

 
[Need any further assistance to fix cPanel errors? – We’re available 24*7]

Conclusion

The “MySQLdump: got error :1049 :unknown database ” triggers while performing cPanel backups. This can happen when the database does not exist in MySQL. Today, we saw how our Support Engineers fix this error.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

SEE SERVER ADMIN PLANS

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Я не могу войти в мою среду разработки учебной базы данных:

Ayman$ mysql -u blog -p blog_development
Enter password: 
ERROR 1049 (42000): Unknown database 'blog_development'

Я могу войти в базу данных отлично без части blog_development:

Ayman$ mysql -u blog -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 1858

Не уверен, что дает, когда я предоставил весь доступ:

mysql> GRANT ALL PRIVILEGES ON blog_development.*
    -> TO 'blog'@'localhost'
    -> IDENTIFIED BY 'newpassword';
Query OK, 0 rows affected (0.01 sec)

mysql> SHOW GRANTS FOR 'blog'@'localhost'
    -> ;
+----------------------------------------------------------------------------------------- --------------------+
 | Grants for [email protected]                                                                                        |
 +----------------------------------------------------------------------------------------- --------------------+
| GRANT USAGE ON *.* TO 'blog'@'localhost' IDENTIFIED BY PASSWORD    '*FE4F2D624C07AAEBB979DA5C980D0250C37D8F63' |
| GRANT ALL PRIVILEGES ON `blog`.* TO 'blog'@'localhost'                                                        |
| GRANT ALL PRIVILEGES ON `blog_development`.* TO 'blog'@'localhost'                                           |
+----------------------------------------------------------------------------------------- --------------------+
3 rows in set (0.00 sec)

Кто-нибудь знает, что попробовать? Благодарю! Кроме того, боковое примечание — это странно, у меня есть несколько пользователей root?:

mysql> select User from mysql.user;
+------+
| User |
+------+
| root |
| root |
|      |
| root |
|      |
| blog |
| root |
+------+
7 rows in set (0.00 sec)

Изменить: для тех, кто спрашивает: я создал блог базы данных с командой CREATE DATABASE в MySql. Вот мои активные базы данных:

mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+  
| information_schema |
| blog               |
| mysql              |
| performance_schema |
| test               |
+--------------------+ 
5 rows in set (0.00 sec)

Based on your comments below your question, it sounds like you probably omitted the --databases option when you used mysqldump to backup the database.

If you backup the databases by doing mysqldump <database-name>, then the backup does not re-create the database for you. When you restore from that backup, you need to create the database that you want to import into and then import into that database, which may or may not be the same name as the database you exported from earlier.

If you do not want to be required to do this, then, when creating your backup, you export like this: mysqldump --databases <database-name>. Doing that, the backup will have the command to re-create the database when it is imported back into MySQL.

There are also other differences between those two usages. If you use the first version, then any symbols after the database name are considered table names to include in the backup. As in: mysqldump MyDatabase Table1 Table2 Table3 to backup tables 1, 2, and 3, but no others.

In the second variation, all symbols after the initial database name are also treated as additional database names, so you can get multiple databases. mysqldump --databases HRDatabase WebsiteDatabase DevTestDatabase That should export all three databases.

But back to the main point: next time you use mysqldump, if you specify the --databases option then you will not need to manually create the database and use it before importing, as that would then be taken care of for you.


For importing the database you need to use mysql not mysqldump in order to create the database automatically (only in case you exported with --databases <database-name> option:
mysql -u root -p < /var/www/html/example.com/backups/backup.sql
(as mentioned in a previous comment by HBruijn,

Using mysqldump for importing your database will not create your database automatically even if you exported it with --databases <database-name> option, these will not work without creating the database first:

mysqldump -u root -p < /var/www/html/example.com/backups/backup.sql
mysqldump --all-databases -u root -p < /var/www/html/example.com/backups/backup.sql
mysqldump --databases mydatabase_name -u root -p < /var/www/html/example.com/backups/backup.sql

Ответ на:

комментарий
от blackst0ne 30.11.13 14:22:02 MSK

Ответ на:

комментарий
от ErasimHolmogorin 30.11.13 14:30:03 MSK

Ответ на:

комментарий
от MikeDM 30.11.13 14:36:14 MSK

Я догадывался, но ИМХО программа специально в дампе это не указывает.

Как это обойти?

Разобрать структуру дампа и самому создать необходимые таблицы, или есть какой-то чудо метод?

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от ErasimHolmogorin 30.11.13 14:39:13 MSK

Ответ на:

комментарий
от MikeDM 30.11.13 14:51:49 MSK

Кликанием мышкой по кнопке.

Файл большой, текстовые редакторы не осиливают.

В общем почему-то только сейчас вспомнил про sed.

Импорт запинается на строке, где TRUNCATE TABLE, собственно думаю, что s/TRUNCATE/CREATE/g должно помочь?

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от ErasimHolmogorin 30.11.13 14:54:57 MSK

это как «кликаньем мышки» может поподробнее расскажешь, я то телепат но не мастер телепат.

MikeDM ★★★★★

(30.11.13 15:05:36 MSK)

  • Показать ответ
  • Ссылка

написать скрипт из двух строк

1. Создание базы

2. Запуск импорта дампа базы.

Alve

★★★★★

(30.11.13 15:06:34 MSK)

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от MikeDM 30.11.13 15:05:36 MSK

Программа для сайта japancar.ru, создаешь базу запчастей у себя на компе, синхронизируешь с сайтом, можно базу экспортировать, но никаких настроек нет, просто кнопка экспорт и все.

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от ErasimHolmogorin 30.11.13 15:10:27 MSK

сделай нормальный mysqldump на сервере и мозги не себе ни людям не насилуй.

MikeDM ★★★★★

(30.11.13 15:12:13 MSK)

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от Alve 30.11.13 15:06:34 MSK

Строки об которые спотыкается импорт.

TRUNCATE TABLE account_type;
INSERT INTO account_type VALUES
('bank', '����', 'adm', '', '2005-11-22 00:00:00', '2005-11-22 16:57:46'),

В данный момент для меня выход создать таблицы по этим данным и уже в них экспортировать, но тут каждую таблицу надо будет создавать вручную. Количество оных мне неизвестно.

  • Ссылка

Ответ на:

комментарий
от MikeDM 30.11.13 15:12:13 MSK

Ответ на:

комментарий
от ErasimHolmogorin 30.11.13 15:18:33 MSK

Ответ на:

комментарий
от MikeDM 30.11.13 15:20:37 MSK

Ответ на:

комментарий
от ErasimHolmogorin 30.11.13 15:22:28 MSK

создай базу autoshop

потом делай импорт так

mysql autoshop -u root -p < db.sql

MikeDM ★★★★★

(30.11.13 15:23:51 MSK)

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от MikeDM 30.11.13 15:23:51 MSK

До этого я уже дошел.

ERROR 1146 (42S02) at line 29: Table 'autoshop.account_type' doesn't exist

Там все выглядит так:

TRUNCATE TABLE account_type;
INSERT INTO account_type VALUES
('bank', '����', 'adm', '', '2005-11-22 00:00:00', '2005-11-22 16:57:46'),
  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от ErasimHolmogorin 30.11.13 15:26:27 MSK

судя по всему дамп делается без схемы создания таблиц.

требуй прямой доступ к базе для снятия дампа.

MikeDM ★★★★★

(30.11.13 15:28:12 MSK)

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от MikeDM 30.11.13 15:28:12 MSK

Ответ на:

комментарий
от ErasimHolmogorin 30.11.13 15:31:36 MSK

Хех, займусь реверсинжинирингом.

1. Пройдись grep’ом по дампу, вытащи все имена таблиц.

2. Сделай отдельный скрипт, где укажи

create table if not exists ...

3. Запусти скрипт — это создаст тебе все нужные таблицы.

4. В дампе убери

Или сразу в дампе замени TRANCATE на CREATE.

  • Ссылка

Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.

Понравилась статья? Поделить с друзьями:
  • Error 1049 42000 unknown database phpmyadmin
  • Error 1049 42000 unknown database mysql
  • Error 1049 42000 unknown database localhost
  • Error 1047 08s01 at line 1 wsrep has not yet prepared node for application use
  • Error 1046 3d000 no database selected что это такое