Ошибка sql 1046 no database selected

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.

The error no database selected frequently occurs in MySQL when you perform a statement without selecting a database first.

In the following example, I tried to query a students table immediately after connecting to the mysql command line:

mysql> SELECT * FROM students;

ERROR 1046 (3D000): No database selected

To resolve this error, you need to first select a database to use in the command line by running the USE command:

You need to replace [database_name] with the name of a database that exists in your MySQL server.

You can also list the names of all databases available on your server with the SHOW DATABASES command.

The following shows the output on my computer:

mysql> SHOW DATABASES;

+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| school_db          |
| sys                |
| test_db            |
+--------------------+

Next, issue the USE command as shown below:

mysql> USE school_db;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> 

The error should be resolved once mysql responds with Database changed as shown above.

The same applies when you’re using a graphical user interface for managing MySQL databases like MySQL Workbench or Sequel Ace.

Just run the USE command before running any other statements:

USE school_db;
SELECT * FROM students;
SELECT * FROM cities;

The error can also happen when you run a .sql script file from the command line without adding a USE command:

mysql -uroot -p < ./files/query.sql
Enter password: 

ERROR 1046 (3D000) at line 1: No database selected

To run the .sql file, you need to add a USE statement inside the SQL file itself.

Alternatively, you can also select the database you want to use from the command line as follows:

mysql -uroot -p school_db < ./files/query.sql   
Enter password: 

id	name
3	Bristol
4	Liverpool
1	London
2	York

You need to add your database name after the -p option and before the < symbol.

And that’s how you can resolve the error no database selected in MySQL database server 😉

Страницы 1

Чтобы отправить ответ, вы должны войти или зарегистрироваться

1 2009-01-24 22:44:24

  • BadMoroz
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2009-01-24
  • Сообщений: 3

Тема: ошибка #1046 — No database selected

Привет всем!! У меня такая проблема( При импорте БД пишет такую ошбку #1046 — No database selected

Ошибка

SQL-запрос:

CREATE TABLE `jos_banner` (
`bid` int( 11 ) NOT NULL AUTO_INCREMENT ,
`cid` int( 11 ) NOT NULL default ‘0’,
`type` varchar( 30 ) NOT NULL default ‘banner’,
`name` varchar( 255 ) NOT NULL default »,
`alias` varchar( 255 ) NOT NULL default »,
`imptotal` int( 11 ) NOT NULL default ‘0’,
`impmade` int( 11 ) NOT NULL default ‘0’,
`clicks` int( 11 ) NOT NULL default ‘0’,
`imageurl` varchar( 100 ) NOT NULL default »,
`clickurl` varchar( 200 ) NOT NULL default »,
`date` datetime default NULL ,
`showBanner` tinyint( 1 ) NOT NULL default ‘0’,
X`checked_out` tinyint( 1 ) NOT NULL default ‘0’,
`checked_out_time` datetime NOT NULL default ‘0000-00-00 00:00:00’,
`editor` varchar( 50 ) default NULL ,
`custombannercode` text,
`catid` int( 10 ) unsigned NOT NULL default ‘0’,
`description` text NOT NULL ,
`sticky` tinyint( 1 ) unsigned NOT NULL default ‘0’,
`ordering` int( 11 ) NOT NULL default ‘0’,
`publish_up` datetime NOT NULL default ‘0000-00-00 00:00:00’,
`publish_down` datetime NOT NULL default ‘0000-00-00 00:00:00’,
`tags` text NOT NULL ,
`params` text NOT NULL ,
PRIMARY KEY ( `bid` ) ,
KEY `viewbanner` ( `showBanner` ) ,
KEY `idx_banner_catid` ( `catid` )
) ENGINE = MYISAM DEFAULT CHARSET = utf8 AUTO_INCREMENT =1

2 Ответ от Hanut 2009-01-25 01:53:52

  • Hanut
  • Hanut
  • Модератор
  • Неактивен
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,726

Re: ошибка #1046 — No database selected

BadMoroz
Сперва выберите (создайте, если надо) БД, в которую вы осуществляете импорт.

3 Ответ от BadMoroz 2009-01-25 15:06:44

  • BadMoroz
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2009-01-24
  • Сообщений: 3

Re: ошибка #1046 — No database selected

Hanut сказал:

BadMoroz
Сперва выберите (создайте, если надо) БД, в которую вы осуществляете импорт.

БД создана и выбрана. всёравно выкидывае ошибку((( #1046

4 Ответ от BadMoroz 2009-01-25 15:14:21

  • BadMoroz
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2009-01-24
  • Сообщений: 3

Re: ошибка #1046 — No database selected

Hanut сказал:

BadMoroz
Сперва выберите (создайте, если надо) БД, в которую вы осуществляете импорт.

Простите за невнимательность все загрузил! Большое спасибо

5 Ответ от Игорь Карасёв 2009-11-20 18:30:06

  • Игорь Карасёв
  • Редкий гость
  • Неактивен
  • Зарегистрирован: 2009-11-20
  • Сообщений: 6

Re: ошибка #1046 — No database selected

BadMoroz Расскажи как справился с проблемой?

6 Ответ от pritvorshik 2013-01-30 12:03:51

  • pritvorshik
  • Новичок
  • Неактивен
  • Зарегистрирован: 2013-01-30
  • Сообщений: 1

Re: ошибка #1046 — No database selected

Нужно слева в списке выбрать базу данных нажав на нее если она уже создана и лишь после импортировать файл имябазы.sql
Либо если там ее нет то создать, выбрать нажав на нее и лишь после импортировать файл с базой данных.
Так же если на хостинге разрешена лишь одна база данных с большим количеством мб, а сайтов можно создать более одного, два,  три и больше то ты просто меняешь либо добавляешь другой префикс к примеру на первый сайт префикс  ya_  на второй ti_  и в той же базе можешь повесить не один сайт c одной базой данных, с учетом если позволяет размер выделенный на базу хостером.

Страницы 1

Чтобы отправить ответ, вы должны войти или зарегистрироваться

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

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

Поделиться

Ещё вопросы

  • 1Получить уровень «подписи» на Android
  • 0Как я могу заполнить массив в datagridview?
  • 1как я могу преобразовать это, чтобы использовать Rx, а не события стиля .NET?
  • 0Проблема с cin.peek () и проблемы с получением правильного ввода
  • 1Линейный поиск по указанному массиву, чтобы получить требуемый индекс элемента
  • 1Добавление изображения из ресурсов в XAML
  • 1Как мне ждать, пока мои данные не будут получены из Firebase? [Дубликат]
  • 0угловой ремешок в сторону не убивает наблюдателя при закрытии
  • 0Как вычесть количество моих продуктов, перечисленных в списке, непосредственно в мою базу данных продуктов? (Баз данных)
  • 0Скрипт запуска Drupal jQuery для .resize ()
  • 1Формат аудио потока гобоя: исчезнет ли формат int16_t?
  • 0Скелетная страница css подменю ie7
  • 1Озадаченный чем-то в методе .reduce () (Javascript)
  • 0проблема в кнопке выхода FB
  • 0Добавление 2d массива
  • 0Google Places хранит результаты в Mysql с PHP
  • 1Как я могу показать два действия на одном экране?
  • 0Angular JS — получить высоту элемента в директиве перед визуализацией представления
  • 0Объектная модель G ++
  • 1Получение FileNotFoundException при попытке поделиться MP3 через неявное намерение с использованием FileProvider
  • 0Сайт учебник, написанный на html / js?
  • 0Как использовать угловые не против разделения кода?
  • 1Не удается получить электронную почту пользователя с интеграцией Facebook
  • 1Разобрать данные Json в объект Json
  • 0Центрировать элемент HTML в WebView
  • 1ошибка при использовании двойной универсальности
  • 1BluetoothDevice.aliasName неразрешенная ссылка
  • 1Ошибка при выходе из окна Jframe
  • 0PHP date_timezone_set не позволяет формату даты показывать время 24 часа
  • 0Идентификатор возвращает 0 для API отдыха с Go
  • 1Аутентификация Firebase createUserWithEmailAndPassword не выполняется на физических устройствах с переменной для электронной почты
  • 1Regexp с .exec не работает
  • 1Javascript, имя функции с интерполяцией строк [дубликаты]
  • 0Как вставить вывод сложной команды терминала linux в таблицу базы данных mysql
  • 1Расчет площади руки с использованием данных о глубине
  • 1Добавление нескольких списков в PivotItem в Windows Phone 7
  • 0Генерация матрицы с помощью std :: generate
  • 0Проверьте, существует ли элемент в двумерном массиве C ++
  • 1Негативное правило для EJB WS
  • 0Как я могу прочитать файл со строками разного количества чисел
  • 0плагин проверки jQuery не проверяет мои формы
  • 1Интерполяция в пандах по горизонтали не зависит от каждой строки
  • 1Проверьте несколько строк (из файла) в отношении текста HTML с Python
  • 0Беда с setlocale
  • 0Используйте один селектор и проверьте местоположение, где щелкнули с помощью jQuery
  • 1Как объединить значения из групп в столбце в Python
  • 1Элемент управления <DNN: ICON> не поддерживает CssClass
  • 1Число больше 9 начинается сверху и остается там
  • 0Загрузка файла $ _FILES массив пуст
  • 1Получить информацию о поле Peoplepicker из другого списка в Sharepoint 2013

Понравилась статья? Поделить с друзьями:
  • Ошибка r keeper 7 545
  • Ошибка sql 01427
  • Ошибка smtp при сканировании
  • Ошибка stop bremsen fehler betriebs anleitung
  • Ошибка sql 1044