Mysql workbench ошибка 1046

Error
SQL query:

--
-- Database: `work`
--
-- --------------------------------------------------------
--
-- Table structure for table `administrators`
--
CREATE TABLE IF NOT EXISTS `administrators` (

`user_id` varchar( 30 ) NOT NULL ,
`password` varchar( 30 ) NOT NULL ) ENGINE = InnoDB DEFAULT CHARSET = latin1;

MySQL said:

#1046 - No database selected

need some help here.

OMG Ponies's user avatar

OMG Ponies

326k82 gold badges523 silver badges502 bronze badges

asked Oct 23, 2010 at 18:19

steph's user avatar

3

You need to tell MySQL which database to use:

USE database_name;

before you create a table.

In case the database does not exist, you need to create it as:

CREATE DATABASE database_name;

followed by:

USE database_name;

Piero's user avatar

Piero

9,17318 gold badges90 silver badges160 bronze badges

answered Oct 23, 2010 at 18:21

codaddict's user avatar

codaddictcodaddict

446k82 gold badges492 silver badges529 bronze badges

4

You can also tell MySQL what database to use (if you have it created already):

 mysql -u example_user -p --database=example < ./example.sql

Daryl Gill's user avatar

Daryl Gill

5,48410 gold badges37 silver badges69 bronze badges

answered Feb 17, 2014 at 19:21

Shay Anderson's user avatar

1

I faced the same error when I tried to import a database created from before. Here is what I did to fix this issue:

1- Create new database

2- Use it by use command

enter image description here

3- Try again

This works for me.

HoldOffHunger's user avatar

HoldOffHunger

18.9k10 gold badges105 silver badges133 bronze badges

answered Dec 6, 2015 at 8:26

Mina Fawzy's user avatar

Mina FawzyMina Fawzy

20.9k17 gold badges133 silver badges156 bronze badges

1

If you’re trying to do this via the command line…

If you’re trying to run the CREATE TABLE statement from the command line interface, you need to specify the database you’re working in before executing the query:

USE your_database;

Here’s the documentation.

If you’re trying to do this via MySQL Workbench…

…you need to select the appropriate database/catalog in the drop down menu found above the :Object Browser: tab. You can specify the default schema/database/catalog for the connection — click the «Manage Connections» options under the SQL Development heading of the Workbench splash screen.

Addendum

This all assumes there’s a database you want to create the table inside of — if not, you need to create the database before anything else:

CREATE DATABASE your_database;

answered Oct 23, 2010 at 18:24

OMG Ponies's user avatar

OMG PoniesOMG Ponies

326k82 gold badges523 silver badges502 bronze badges

4

For MySQL Workbench

  1. Select database from Schemas tab by right mouse clicking.
  2. Set database as Default Schema

enter image description here

answered Dec 6, 2018 at 14:12

Eric Korolev's user avatar

1

If you are doing this through phpMyAdmin:

  • I’m assuming you already Created a new MySQL Database on Live Site (by live site I mean the company your hosting with (in my case Bluehost)).

  • Go to phpMyAdmin on live site — log in to the database you just created.

  • Now IMPORTANT! Before clicking the «import» option on the top bar, select your database on the left side of the page (grey bar, on the top has PHP Myadmin written, below it two options:information_schema and name of database you just logged into.

  • once you click the database you just created/logged into it will show you that database and then click the import option.

That did the trick for me. Really hope that helps

andrewtweber's user avatar

andrewtweber

24.6k22 gold badges88 silver badges110 bronze badges

answered Mar 18, 2014 at 1:25

Roanna's user avatar

RoannaRoanna

2512 silver badges2 bronze badges

2

Assuming you are using the command line:

1. Find Database

show databases;

Example of a database list

2. Select a database from the list

e.g. USE classicmodels; and you should be off to the races! (Obviously, you’ll have to use the correctly named database in your list.

Why is this error occurring?

Mysql requires you to select the particular database you are working on. I presume it is a design decision they made: it avoids a lot of potential problems: e.g. it is entirely possible, for you to use the same table names across multiple databases e.g. a users table. In order to avoid these types of issues, they probably thought: «let’s make users select the database they want».

answered Dec 12, 2020 at 23:44

BenKoshy's user avatar

BenKoshyBenKoshy

33.5k14 gold badges111 silver badges80 bronze badges

  • Edit your SQL file using Notepad or Notepad++
  • add the following 2 line:

CREATE DATABASE NAME;
USE NAME;

ckpepper02's user avatar

ckpepper02

3,2975 gold badges29 silver badges43 bronze badges

answered Oct 11, 2013 at 20:48

Ayham AlKawi's user avatar

1

If importing a database, you need to create one first with the same name, then select it and then IMPORT the existing database to it.

Hope it works for you!

answered Oct 25, 2011 at 16:38

ivan n's user avatar

ivan nivan n

991 silver badge1 bronze badge

1

Check you have created the database first which you want.

If you have not created the dataBase you have to fire this query:

CREATE DATABASE data_base_name

If you have already created the database then you can simply fire this query and you will be able to create table on your database:

CREATE TABLE `data_base_name`.`table_name` (
 _id int not null,
 LastName varchar(255) NOT NULL,
 FirstName varchar(255),
 Age int,
 PRIMARY KEY (_id)
);

answered Apr 7, 2021 at 6:22

Sanket H patel's user avatar

Solution with an Example

  • Error 1046 occurs when we miss to connect our table with a database. In this case, we don’t have any database and that’s why at first we will create a new database and then will instruct to use that database for the created table.
# At first you have to create Database 
CREATE DATABASE student_sql;

# Next, specify the database to use
USE student_sql;

# Demo: create a table 
CREATE TABLE student_table(
    student_id INT PRIMARY KEY,
    name VARCHAR(20),
    major VARCHAR(20)
);

# Describe the table 
describe student_table;

answered May 28, 2022 at 20:02

sargupta's user avatar

sarguptasargupta

94313 silver badges25 bronze badges

quoting ivan n :
«If importing a database, you need to create one first with the same name, then select it and then IMPORT the existing database to it.
Hope it works for you!»

These are the steps:
Create a Database, for instance my_db1, utf8_general_ci.
Then click to go inside this database.
Then click «import», and select the database: my_db1.sql

That should be all.

answered Apr 18, 2013 at 12:25

iversoncru's user avatar

iversoncruiversoncru

5798 silver badges22 bronze badges

1

first select database : USE db_name

then creat table:CREATE TABLE tb_name
(
id int,
name varchar(255),
salary int,
city varchar(255)
);

this for mysql 5.5 version syntax

answered Jul 4, 2015 at 12:46

veeru666's user avatar

I’m late i think :] soory,

If you are here like me searching for the solution when this error occurs with mysqldump instead of mysql, try this solution that i found on a german website out there by chance, so i wanted to share with homeless people who got headaches like me.

So the problem occurs because the lack -databases parameter before the database name

So your command must look like this:

mysqldump -pdbpass -udbuser --databases dbname

Another cause of the problem in my case was that i’m developping on local and the root user doesn’t have a password, so in this case you must use --password= instead of -pdbpass, so my final command was:

mysqldump -udbuser --password= --databases dbname

Link to the complete thread (in German) : https://marius.bloggt-in-braunschweig.de/2016/04/29/solution-mysqldump-no-database-selected-when-selecting-the-database/

answered Sep 23, 2018 at 2:52

moolsbytheway's user avatar

In Amazon RDS, merely writing use my-favorite-database does not work if that database’s name includes dashes. Furthermore, none of the following work, either:

use "my-favorite-database"
use `my-favorite-database`
use 'my-favorite-database'

Just click the «Change Database» button, select the desired database, and voilà.

answered Sep 8, 2021 at 18:21

David's user avatar

DavidDavid

8958 silver badges12 bronze badges

Although this is a pretty old thread, I just found something out. I created a new database, then added a user, and finally went to use phpMyAdmin to upload the .sql file. total failure. The system doesn’t recognize which DB I’m aiming at…

When I start fresh WITHOUT first attaching a new user, and then perform the same phpMyAdmin import, it works fine.

answered Sep 27, 2013 at 10:15

zipzit's user avatar

zipzitzipzit

3,7864 gold badges35 silver badges63 bronze badges

Just wanted to add: If you create a database in mySQL on a live site, then go into PHPMyAdmin and the database isn’t showing up — logout of cPanel then log back in, open PHPMyAdmin, and it should be there now.

answered Aug 4, 2014 at 23:42

the10thplanet's user avatar

For an added element of safety, when working with multiple DBs in the same script you can specify the DB in the query, e.g. «create table my_awesome_db.really_cool_table…».

answered Jul 17, 2016 at 15:36

William T. Mallard's user avatar

Simple

  1. click on database
  2. and then click on import

without modifying .sql file

answered Aug 12 at 11:34

Joukhar's user avatar

JoukharJoukhar

7041 gold badge3 silver badges18 bronze badges

jst create a new DB in mysql.Select that new DB.(if you r using mysql phpmyadmin now on the top it’l be like ‘Server:...* >> Database ).Now go to import tab select file.Import!

answered Oct 19, 2015 at 5:34

cs075's user avatar

0

ProgrammerAH

Programmer Guide, Tips and Tutorial

A bug in mysql Workbench:
Error Code: 1046. No database selected Select the default DB to be used by double-clicking its name in the SCHEMAS list in the sidebar.

Reason: Database was not selected
Solution: Double-click on the JSTZ post to execute the SQL Script

Read More:

15 ответов

Вам нужно указать MySQL, какую базу данных использовать:

USE database_name;

прежде чем создавать таблицу.

Если база данных не существует, вам необходимо создать ее как:

CREATE DATABASE database_name;

а затем:

USE database_name;

codaddict

Поделиться

Вы также можете указать MySQL, какую базу данных использовать (если она уже создана):

 mysql -u example_user -p --database=example < ./example.sql

Shay Anderson

Поделиться

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

1- Создать новую базу данных

2- Используйте его с use команды

Изображение 881

3- Повторите попытку

Это работает для меня.

Mina Fawzy

Поделиться

Если вы пытаетесь сделать это с помощью командной строки…

Если вы пытаетесь запустить оператор CREATE TABLE из интерфейса командной строки, вам нужно указать базу данных, в которой вы работаете, перед выполнением запроса:

USE your_database;

Здесь документация.

Если вы пытаетесь сделать это через MySQL Workbench…

… вам нужно выбрать соответствующую базу данных/каталог в раскрывающемся меню, расположенном над вкладкой «Обозреватель объектов: вкладка». Вы можете указать стандартную схему/базу данных/каталог для подключения — нажмите «Управление соединениями» в разделе «Развитие SQL» экрана заставки Workbench.

Добавление

Все это предполагает наличие базы данных, в которой вы хотите создать таблицу внутри — если нет, вам нужно создать базу данных прежде всего:

CREATE DATABASE your_database;

OMG Ponies

Поделиться

Если вы делаете это через phpMyAdmin:

  • Я предполагаю, что вы уже создали новую базу данных MySQL на Live-сайте (на живом сайте я имею в виду компанию, в которой ваш хостинг (в моем случае Bluehost)).

  • Перейдите в phpMyAdmin на сайте live — войдите в базу данных, которую вы только что создали.

  • Теперь ВАЖНО! Прежде чем нажимать кнопку «импорт» на верхней панели, выберите свою базу данных в левой части страницы (серая полоса, сверху вверху написан PHP Myadmin, под ней два параметра: information_schema и имя базы данных, в которую вы только вошли.

  • после того, как вы щелкнете базу данных, которую вы только что создали/вошли в нее, она покажет вам эту базу данных и затем щелкните параметр импорта.

Это трюк для меня. Надеюсь, что поможет

Roanna

Поделиться

  • Отредактируйте свой SQL файл, используя Блокнот или Блокнот ++
  • добавьте следующую строку:

CREATE DATABASE NAME;
USE NAME;

Ayham AlKawi

Поделиться

Если вы импортируете базу данных, вам нужно сначала создать ее с тем же именем, затем выбрать ее, а затем импортировать в нее существующую базу данных.

Надеюсь, что это сработает для вас!

ivan n

Поделиться

цитирование ivan n:
«Если вы импортируете базу данных, вам нужно сначала создать ее с тем же именем, а затем выбрать ее, а затем импортировать в нее существующую базу данных.
Надеюсь, это сработает для вас! «

Это следующие шаги:
Создайте базу данных, например my_db1, utf8_general_ci.
Затем нажмите, чтобы войти в эту базу данных.
Затем нажмите «импорт» и выберите базу данных: my_db1.sql

Это должно быть все.

iversoncru

Поделиться

сначала выберите базу данных: USE db_name

тогда таблица creat: CREATE TABLE tb_name
(  id int,
 имя varchar (255),
 зарплата int, город варчар (255)
);

this для синтаксиса версии mysql 5.5

veeru666

Поделиться

Для MySQL Workbench

  1. Выберите базу данных со вкладки Схемы, щелкнув правой кнопкой мыши.
  2. Установить базу данных как схему по умолчанию

Изображение 882

Eric Korolev

Поделиться

Я опаздываю, думаю:] Сори,

Если вы здесь, как я, ища решение, когда эта ошибка возникает с mysqldump вместо mysql, попробуйте это решение, которое я нашел на немецком веб-сайте, случайно, поэтому я хотел поделиться с бездомными людьми, у которых были головные боли, подобные мне.

Таким образом, проблема возникает из-за отсутствия параметра -databases перед именем базы данных

Поэтому ваша команда должна выглядеть так:

mysqldump -pdbpass -udbuser --databases dbname

Другая причина проблемы в моем случае заключалась в том, что я развивается на локальном компьютере, а у пользователя root нет пароля, поэтому в этом случае вы должны использовать --password= вместо -pdbpass, поэтому моя последняя команда:

mysqldump -udbuser --password= --databases dbname

Ссылка на полный поток (на немецком языке): https://marius.bloggt-in-braunschweig.de/2016/04/29/solution-mysqldump-no-database-selected-when-selecting-the-database/

MoolsBytheway

Поделиться

Для дополнительного элемента безопасности при работе с несколькими БД в том же script вы можете указать БД в запросе, например. msgstr «создать таблицу my_awesome_db.really_cool_table…».

William T. Mallard

Поделиться

Просто хотел добавить: если вы создаете базу данных в mySQL на живом сайте, перейдите в PHPMyAdmin, и база данных не появится — выход из cPanel, затем войдите в систему, откройте PHPMyAdmin, и он должен быть там сейчас.

the10thplanet

Поделиться

Хотя это довольно старый поток, я только что нашел что-то. Я создал новую базу данных, затем добавил пользователя и, наконец, пошел использовать phpMyAdmin для загрузки файла .sql. общий сбой. Система не распознает, к какой базе данных я стремился…

Когда я начинаю новый БЕЗ с первого присоединения нового пользователя, а затем выполняет тот же импорт phpMyAdmin, он отлично работает.

zipzit

Поделиться

jst создайте новую базу данных в mysql. Выберите этот новый DB. (если вы используете mysql phpmyadmin сейчас, то наверху он будет похож на «Сервер: ... * → База данных). Теперь перейдите на вкладку импорта, выберите файл. Импорт!

cs075

Поделиться

Ещё вопросы

  • 0ng-repeat возвращает TypeError: невозможно прочитать свойство ‘insertBefore’ из null
  • 1Как изменить название пакета Android на Android Studio, добавив раздел?
  • 0Избыточная загрузка углового модуля на нижнем уровне?
  • 0Передача переменной из .htaccess на страницу PHP
  • 0Как вставить скобки в имя столбца моей таблицы SQL?
  • 0c ++ редактировать определенное слово из строки в текстовом файле
  • 0гиперссылка laravel4 не отображается в Yahoo, Outlook, но в Gmail гиперссылка работает
  • 1Служба Windows с FileWatcher не работает должным образом
  • 0Как сделать окно командной строки открытым в верхнем левом углу?
  • 1Парсер DOM для чтения Xml, извлечения значений атрибутов и их хранения
  • 1node.js печатает пользовательский объект перечисления с дополнительным полем [Number], например {[Number: 10] name: ‘Dime’, значение: 10}
  • 1Android: правильное место для создания канала уведомлений
  • 0Угловая лучшая практика. Действия контроллера, запускающие анимацию
  • 1Как создать объект в Form1 из другого класса?
  • 0PHP-код по умолчанию с ошибкой, когда это не должно быть
  • 1Vue директива после V-для
  • 1Как динамически получать изображения подушек в Tkinter
  • 0Я получаю «Усеченное неверное значение даты и времени:« 0000-00-00 »» даже при выключенном строгом режиме.
  • 1FLAG_ACTIVITY_NEW_TASK не открывает предыдущее действие, а только при новой установке apk
  • 1Сортировать список по имени, дате и иерархии
  • 0Div точная высота как высота окна
  • 1Клавиатура Android не отображается при нажатии поля ввода в единстве?
  • 1Ударьте или пропустите морфологию в python, чтобы найти структуры в изображениях, не дает требуемых результатов
  • 1Как нарисовать пользовательскую графику на карте, используя ArcGIS JavaScript API?
  • 1Обрабатывать всплывающее окно JavaScript внутри div
  • 0Оберните кучу вариантов внутри стола в Symfony / Twig
  • 0не может получить 2-й дататабельно свой собственный CSS
  • 0C ++ Соединение двух разделенных на трубы файлов по ключевым полям
  • 1XamDataGrid — добавление столбцов во время выполнения
  • 1Угловая труба: невозможно заменить / n
  • 0Каковы некоторые популярные базы данных на основе строк и столбцов?
  • 1Обновление данных из Vuex дает бесконечный цикл в watcher
  • 0как помешать yii2 выполнить запрос select при вызове Yii :: $ app-> user-> id
  • 0Инструкция выбора AngularJS с нулевым значением
  • 1ItemRegister Iterator
  • 1QueryDocumentSnapshot не может разрешить
  • 0Невозможно загрузить файл на сервер (AngularJS и Perl)
  • 0Угловая проверка разрешений JS
  • 0C ++ Синглтон / Парадигма активного объекта
  • 1Почему потоки не завершают выполнение в Python? Семафоры обеспечивают синхронизацию процессов, но выполнение не завершается
  • 1сбой приложения при добавлении google login firebaseui
  • 1Узел JS Как отправить изображение вместе с запросом данных на другой сервер / API
  • 1Использование глобальных обработчиков исключений и локальных
  • 1Python-pptx: копировать слайд
  • 0Получение информации из нескольких источников с использованием MySQLI и возможность отображать результаты
  • 1Вводить матрицу частот в терминах документа в TfidfVectorizer ()?
  • 1Java JComboBox внешний вид
  • 0Редактирование ячейки JqGrid с использованием редактирования ячейки
  • 0Проблемы компиляции при наследовании от класса, вложенного в шаблон [duplicate]
  • 0Выбор столбцов для вставки в таблицу с условием где

I wrote a stored procedure (sp_archivev3) on MySQl Workbench which is as follows. Basically, Inserting values from one database to another.

-- --------------------------------------------------------------------------------
-- Routine DDL
-- Note: comments before and after the routine body will not be stored by the server
-- --------------------------------------------------------------------------------
DELIMITER $$

CREATE DEFINER=`MailMe`@`%` PROCEDURE `sp_archivev3`()
BEGIN

INSERT INTO 
     send.sgev3_archive(a_bi,
                        b_vc,
                        c_int,
                        d_int,
                        e_vc,
                        f_vc,
                        g_vc,
                        h_vc,
                        i_dt,
                        j_vc,
                        k_vc,
                        l_vc,
                        m_dt,
                        n_vch,
                        o_bit)
SELECT     a_bi,
           b_vc,
           c_int,
           d_int,
           e_vc,
           f_vc,
           g_vc,
           h_vc,
           i_dt,
           j_vc,
           k_vc,
           l_vc,
           m_dt,
           n_vch,
           o_bit

FROM   send.sgev3

WHERE m_dt BETWEEN  '2014-06-09' AND CURDATE();


END

When I run call sp_archivev3(); , I get an error with an error code 1046: No database
selected SELECT the default DB to be used by double-clicking its name in the SCHEMAS list in the sidebar.

Please let me know what’s wrong with my stored procedure.

Mysql no database selected error causesMySQL no database selected is an error that occurs when you execute a statement without first selecting a database. The database may be completely missing, or you may choose the wrong database if there is more than one database.

Therefore, if you have more than one database, know the currently selected database and on which database your query execution takes place. Read this article to understand MySQL error and how to fix it.

Contents

  • MySQL No Database Selected Error Causes
  • How to Resolve the No Database Selected Error During File Import
    • – Create a New Database
    • – Workbench Solution
    • – PhpMyAdmin Error Fix
    • – Other Solutions for Database Not Selected Error
  • How to View Currently Selected Database: Avoiding MySQL No Database Selected Error
  • How to Import Files to Mysql Correctly
  • FAQ
    • – How Do I Switch Between Mysql Databases?
    • – How Do I Select a Schema in Mysql?
  • Conclusion

MySQL No Database Selected Error Causes

The MySQL1046 (3D000) error occurs when you do not select a database first when executing the MySQL statement. This error will mostly happen if you are trying to create a table in the MySQL database using the command prompt. While executing a command from the command prompt, you must also select the database. Otherwise, MySQL will not know from which database you are running the script.

MySQL has a command to help you determine the currently selected database. This is a quick way to help you ascertain if the problem is genuinely caused by not specifying a database. If the error arises due to not selecting a database, you can easily overcome it by replacing [database_name] with the correct database name in your server.

When creating a table statement from the MySQL workbench, you need to select the database to run before executing the statement. Note, the process of choosing the database is manual, not automatic. Similarly, when running a script from the command prompt screen, ensure that you provide that database name.

How to Resolve the No Database Selected Error During File Import

The error code 1046 no database selected MySQL workbench will pop up if you do not select a database before importing the SQL file. This can be disappointing if you do not know the origin of the problem. Now that you know the reason, here are some quick fixes.

– Create a New Database

  • You must mention the name of the database prior to creating a table. To do so, use the command: USE database_name;
  • If the database is not there, create a new database. Creating a new database can be quickly done by using the command: CREATE DATABASE database_name;

Now, use the newly created database with the command USE database_name. This should eliminate the 1046 error.

– Workbench Solution

This solution is specifically efficient when using the workbench. Experts suggest that you follow the steps below to eliminate the error:

  • Find the welcome window, navigate to the left pane, and Object the browser
  • From the drop-down list, select a database of interest
  • Go to the SQL Development in the Workbench splash screen, look for the Manage Connections icon, and click on it.

– PhpMyAdmin Error Fix

This solution works for No database selected PhpMyAdmin errors. The approach tells you how you can resolve the error during the import. Just follow the steps below:

  • Have a new database ready on Live Site (the company hosting you, e.g., Bluehost). This is mandatory.
  • Navigate to phpMyAdmin on the live site and log in to the database
  • Choose a database of interest from the list on the left side of the page. Usually, there is a grey bar on top with a PHPMyadmin inscription, and below it are two options – information_schema and the name of the database you logged into.
  • From the top bar, click on the import button.
  • Find and click on the Browse button, browse the files to find the SQL file you created or of interest and click to open it when you see it. If the file is zipped, unzip it first.
  • Select SQL as the file format and press the Go button

After pressing the Go button, you will wait for a few minutes before seeing the results. Typically, the amount of wait time depends on the size of the database. The name of the created database must be similar to the name mentioned in the file. Otherwise, it will still throw the error.

– Other Solutions for Database Not Selected Error

One of the solutions requires that you create a database first before importing it. Here is the procedure.

  • Create a new database using MySQL phpMyAdmin
  • Use the database by simply running the command use database_name

And, finally, the easiest solution among all as it allows you to select a database using the command:

mysql -u example_user -p –database=work < ./work.sql

How to View Currently Selected Database: Avoiding MySQL No Database Selected Error

If you want to view the presently selected database, use the MySQL command below:

SELECT DATABASE();

You can execute this command from both two points – MySQL command line or MySQL workbench. The procedure for both processes is pretty straightforward.

If you are accessing it from the workbench, open it and execute the command:

SELECT DATABASE();

This action will expose the currently selected database, i.e., it returns the database you have selected. Usually, the database is also displayed in bold on the left side.

If you are working from the MySQL terminal, you must log in using your username and password and execute the command:

SELECT DATABASE();

This action also presents the selected database. However, the command will return null if you have not selected a database. This is common when you log into the terminal for the first time.

How to Import Files to Mysql Correctly

When the error emerges on your screen, you know the real cause of the issue. But, do you know how to select the database in MySQL? So, if you encounter a ”no database selected” error in PHP, Python, or any other program, you didn’t import your file correctly. Here is how you can import the files:

1. The step one is opening the Command :

  • Open the command prompt on MySQL
  • Navigate to the start menu and open Command Line Client.

2. The second step is selecting the Database:

  • Selecting the database takes two forms: first, if you know the database, and second, if you do not know the database.

3. Let’s look at the first case (you know the database name):

  • Select the database you wish to execute your script
  • Do you know the name of the database? If yes, enter it in the format, use <database_name>;

Knowing the database name is critical since it is a solution to getting rid of the 1046 (3D000) error message.

4. Let’s look at the second option (you do not know the database name):

  • In case you don’t know the database or database name on which you want to execute the script, list all the databases available using the command SHOW databases;
  • This command, i.e., SHOW databases, will list all available databases making it easy to spot the database of interest.
  • Run the use <database_name> command to select the database you want

5. And now we can execute the Statement:

  • After you successfully select a database of interest, execute the needed statement. Typically, you will be executing create table statement in the database. This action creates a table in the database in MySQL using the workbench.

FAQ

– How Do I Switch Between Mysql Databases?

If you have more than one database in MySQL, indicate each with the USE command. This command helps you select or switch between databases in a MySQL server. However, you must choose the correct database each time you switch databases or start a new MySQL session.

– How Do I Select a Schema in Mysql?

Right-click on MySQL connection from the home screen and select edit connect. Set the desired default schema on the Default Schema box. The schema you select will be displayed in bold in the schema navigator. Use Filter to This Schema functionality to target specific schemas in the list.

Conclusion

Error 1046 usually occurs if you do not select the correct database when importing files in MySQL. That’s what we have discussed in detail in this article. The main points in this article are:

  • Always select the database before clicking the import button
  • Use the command SELECT Database when selecting a specific database in MySQL to work with when you have multiple databases. However, if you have one database, use SQL command USE.
  • When MySQL ERROR 1046 (3D000) occurs, ensure you select the database. You can use the exact name to locate the file. Otherwise, use the command SHOW databases. This command displays all databases letting you select the right one.
  • The first step in preventing the 1046 error is learning how to import files.

How to fix mysql no database selected errorFirst, we have shown you how to import files correctly, and second, we have given you tips on how to solve the error 1046 when it occurs. These fixes are pretty straightforward, so why can’t you start applying them today?

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

Понравилась статья? Поделить с друзьями:
  • Mysql installer accounts and roles ошибка
  • Mysql insert игнорировать ошибки
  • Mysql innodb проверка базы на ошибки
  • Mysql fetch assoc ошибка
  • Mysql 500 ошибка