Меню

Ошибка 1046 mysql workbench

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

321k79 gold badges516 silver badges499 bronze badges

asked Oct 23, 2010 at 18:19

steph's user avatar

2

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,06318 gold badges88 silver badges158 bronze badges

answered Oct 23, 2010 at 18:21

codaddict's user avatar

codaddictcodaddict

440k80 gold badges490 silver badges526 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,4149 gold badges36 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

answered Dec 6, 2015 at 8:26

Mina Fawzy's user avatar

Mina FawzyMina Fawzy

20.5k16 gold badges129 silver badges149 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

321k79 gold badges516 silver badges499 bronze badges

4

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

23.7k22 gold badges86 silver badges109 bronze badges

answered Mar 18, 2014 at 1:25

Roanna's user avatar

RoannaRoanna

2512 silver badges2 bronze badges

2

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

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

CREATE DATABASE NAME;
USE NAME;

ckpepper02's user avatar

ckpepper02

3,2675 gold badges28 silver badges43 bronze badges

answered Oct 11, 2013 at 20:48

Ayham AlKawi's user avatar

1

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

31.9k14 gold badges101 silver badges78 bronze badges

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

be careful about blank passwords

mysqldump [options] -p '' --databases database_name

will ask for a password and complain with mysqldump: Got error: 1046: "No database selected" when selecting the database

the problem is that the -p option requires that there be no space between -p and the password.

mysqldump [options] -p'' --databases database_name

solved the problem (quotes are not needed anymore).

answered Jul 22, 2019 at 19:37

user3338098's user avatar

user3338098user3338098

9361 gold badge17 silver badges36 bronze badges

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

91712 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

5678 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

7576 silver badges11 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,5584 gold badges32 silver badges58 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

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

Содержание

  1. [FIX] MySQL ERROR 1046 (3D000) No Database Selected
  2. Why you are getting MySQL Error 1046 (3D000) No database selected?
  3. Steps to resolve MySQL ERROR 1046 (3D000) No Database Selected:
  4. Step 1:
  5. Step 2: Select the database
  6. Step 3: Execute statement
  7. Conclusion:
  8. SQL Error 1046 – Resolve it now
  9. What causes SQL error 1046 to occur
  10. How we fix SQL error 1046
  11. Conclusion
  12. PREVENT YOUR SERVER FROM CRASHING!
  13. Ошибка 1046 Нет базы данных Выбран, как решить?
  14. 15 ответов
  15. Если вы пытаетесь сделать это с помощью командной строки.
  16. Если вы пытаетесь сделать это через MySQL Workbench.
  17. Добавление
  18. ошибка #1046 — No database selected
  19. Сообщения 6
  20. 1 Тема от BadMoroz 2009-01-24 22:44:24
  21. Тема: ошибка #1046 — No database selected
  22. 2 Ответ от Hanut 2009-01-25 01:53:52
  23. Re: ошибка #1046 — No database selected
  24. 3 Ответ от BadMoroz 2009-01-25 15:06:44
  25. Re: ошибка #1046 — No database selected
  26. 4 Ответ от BadMoroz 2009-01-25 15:14:21
  27. Re: ошибка #1046 — No database selected
  28. 5 Ответ от Игорь Карасёв 2009-11-20 18:30:06
  29. Re: ошибка #1046 — No database selected
  30. 6 Ответ от pritvorshik 2013-01-30 12:03:51
  31. Re: ошибка #1046 — No database selected
  32. Сообщения 6
  33. Ошибка 1046 Нет базы данных Выбран, как решить?
  34. Если вы пытаетесь сделать это через командную строку .
  35. Если вы пытаетесь сделать это через MySQL Workbench .
  36. добавление

[FIX] MySQL ERROR 1046 (3D000) No Database Selected

This article is a step-by-step guide to resolve the “MySQL ERROR 1046 (3D000) No Database Selected” error. If you are a DBA or a developer, this post will help you fix this MySQL 1046 error.

If you are getting this error message means you are trying to execute MySQL queries statement using the MySQL command prompt. Let’s go through why we get the error 1046 (3D000) followed by the step-by-step procedure to resolve this error.

Why you are getting MySQL Error 1046 (3D000) No database selected?

Let me tell you first why you are getting this 1046 MySQL error message. You might have guessed it right by now; the error message is pretty clear that you have not selected the database before executing your MySQL statement.

This error generally occurs when you try to create a Table in the MySQL database using the command prompt.

Because while executing a command from the command prompt you need to select the database also since MySQL will not be able to know for which database you are executing the script.

When you execute create table statement from MySQL workbench then at that time you need to manually select the database then you execute your statement. Similarly, while executing a script from the command prompt screen, make sure you have provided the database name.

The next question is “how to provide the database name?” No worries. Here are the steps; just follow the below steps by step procedure to get rid of the error.

Steps to resolve MySQL ERROR 1046 (3D000) No Database Selected:

Step 1:

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

Step 2: Select the database

If you know the database name:

  • Select the Database on which you want to execute your script.
  • If you know the name of the database, then enter the database name in the following format.

use ;

Note: Don’t skip this step, this is the solution to get rid of the 1046 (3D000) error message.

If you do not know the database name:

If you don’t know the available database names or the database on which you are going to execute the script, then you can list all available databases using the following command.

SHOW databases;

Show database command lists down all the databases available. Then you run use ;

Step 3: Execute statement

Once the database is selected, you can execute your required SQL statement. Here we will execute create table statement in the database as an example.

That’s it. You can see the created table in the MySQL database using MySQL workbench.

Conclusion:

Is it not simple? I hope you now know the reason behind the “MySQL error 1046 No Database selected error” issue and how to fix it. Do share your feedback if this post helped you to fix the MySQL 1046 (3D000) error using the above steps in the comment section.

Источник

SQL Error 1046 – Resolve it now

SQL error 1046 occurs if the database is not selected.

Here at Bobcares, we have seen several such SQL related issues as part of our Server Management Services for web hosts and online service providers.

Today we’ll take a look at the cause for this error and how to fix it.

What causes SQL error 1046 to occur

Generally, this error occurs when creating tables or while recovering the tables from any backup.

For example, let’s say that we have created a database and provided a password as well.
Now while creating the table if we forget to mention the database name then we will end up with this error message.

This happens because SQL is not aware of which database we are going to use.

Also, the same goes while importing tables from any backup.

For instance, the error appears as below.

How we fix SQL error 1046

Now let’s look into different solutions provided by our Support Engineers.

1. Recently, one of our customers approached us with the same error message while creating a table.

We then replicated the error and could find that the customer wasn’t selecting the database to create a table.

So we suggested running the below command so that the database gets selected.

In case, if the database doesn’t exist then we ask customers to create it via below command

After this step, we suggested the customer create the tables. Finally, he was able to create it with no more errors.

2. Alternately, we also provide the below command to select the database.

3. In some situations, if the customer has the database file then we import the database in phpMyAdmin for them. Here are the steps that we follow to do so.

  • First, we access the phpMyAdmin. Then select the database created by the customer from the list of databases on the left of the page.
  • Here, we click on the Import option available on the top bar.
  • Then click on the ‘Browse‘ button available next to the ‘Location of the SQL file‘.
  • Here, we browse the local SQL file and open it. After that, we choose the format as ‘SQL‘.
  • Finally, we click on the ‘Go‘ button and wait for the database to get imported.

NOTE: We follow the above steps to import the database only after creating it.

[Need any further assistance in fixing SQL errors? – We’re available 24*7]

Conclusion

In short, this error can arise if we forget to select the database before creating tables or importing .sql file. Today, we saw the resolution to this SQL 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.

Источник

Ошибка 1046 Нет базы данных Выбран, как решить?

нужна помощь здесь.

15 ответов

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

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

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

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

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

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

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

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

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

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

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

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

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

Добавление

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

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

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

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

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

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

Источник

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

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

Сообщения 6

1 Тема от BadMoroz 2009-01-24 22:44:24

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

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

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

Ошибка

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
  • Модератор
  • Неактивен
  • Откуда: Рига, Латвия
  • Зарегистрирован: 2006-07-02
  • Сообщений: 9,722

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

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

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

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

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

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

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

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

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

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

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 одной базой данных, с учетом если позволяет размер выделенный на базу хостером.

Сообщения 6

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

Источник

Ошибка 1046 Нет базы данных Выбран, как решить?

нужна помощь здесь

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

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

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

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

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

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

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

3- Попробуй еще раз

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

Если вы пытаетесь сделать это через командную строку .

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

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

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

добавление

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

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

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

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

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

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

Это помогло мне. Очень надеюсь, что это помогает

Источник

This article is a step-by-step guide to resolve the “MySQL ERROR 1046 (3D000) No Database Selected” error. If you are a DBA or a developer, this post will help you fix this MySQL 1046 error.

If you are getting this error message means you are trying to execute MySQL queries statement using the MySQL command prompt. Let’s go through why we get the error 1046 (3D000) followed by the step-by-step procedure to resolve this error.

Why you are getting MySQL Error 1046 (3D000) No database selected?

MySQL ERROR 1046 (3D000) No Database Selected

Let me tell you first why you are getting this 1046 MySQL error message.  You might have guessed it right by now; the error message is pretty clear that you have not selected the database before executing your MySQL statement.

This error generally occurs when you try to create a Table in the MySQL database using the command prompt.

Because while executing a command from the command prompt you need to select the database also since MySQL will not be able to know for which database you are executing the script.

When you execute create table statement from MySQL workbench then at that time you need to manually select the database then you execute your statement. Similarly, while executing a script from the command prompt screen, make sure you have provided the database name.

The next question is “how to provide the database name?” No worries. Here are the steps; just follow the below steps by step procedure to get rid of the error.

Steps to resolve MySQL ERROR 1046 (3D000) No Database Selected:

Step 1:

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

MySQL command line client

Step 2: Select the database

If you know the database name:

  • Select the Database on which you want to execute your script.
  • If you know the name of the database, then enter the database name in the following format.

use <database_name>;

select and use a database in MySQL

Note: Don’t skip this step, this is the solution to get rid of the 1046 (3D000) error message.

If you do not know the database name:

If you don’t know the available database names or the database on which you are going to execute the script, then you can list all available databases using the following command.

SHOW databases;

Show database command lists down all the databases available. Then you run use <database_name>;

Show database in MySQL

Step 3: Execute statement

Once the database is selected, you can execute your required SQL statement. Here we will execute create table statement in the database as an example.

mysql create table no database selected fix - table created

That’s it. You can see the created table in the MySQL database using MySQL workbench.

Table created in MySQL

Conclusion:

Is it not simple? I hope you now know the reason behind the “MySQL error 1046 No Database selected error” issue and how to fix it. Do share your feedback if this post helped you to fix the MySQL 1046 (3D000) error using the above steps in the comment section.

Cheers !!!

Similar article:
1. Fix “unknown collation ‘utf8mb4_unicode_520_ci’” Error

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

Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.

Position is Everything

15 ответов

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

USE database_name;

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

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

CREATE DATABASE database_name;

а затем:

USE database_name;

codaddict
23 окт. 2010, в 18:35

Поделиться

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

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

Shay Anderson
17 фев. 2014, в 19:47

Поделиться

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

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

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

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

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

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

Mina Fawzy
06 дек. 2015, в 09:44

Поделиться

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

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

USE your_database;

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

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

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

Добавление

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

CREATE DATABASE your_database;

OMG Ponies
23 окт. 2010, в 19:40

Поделиться

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

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

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

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

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

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

Roanna
18 март 2014, в 01:40

Поделиться

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

CREATE DATABASE NAME;
USE NAME;

Ayham AlKawi
11 окт. 2013, в 21:40

Поделиться

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

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

ivan n
25 окт. 2011, в 17:44

Поделиться

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

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

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

iversoncru
18 апр. 2013, в 13:56

Поделиться

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

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

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

veeru666
04 июль 2015, в 13:13

Поделиться

Для MySQL Workbench

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

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

Eric Korolev
06 дек. 2018, в 14:36

Поделиться

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

Если вы здесь, как я, ища решение, когда эта ошибка возникает с 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
23 сен. 2018, в 03:56

Поделиться

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

William T. Mallard
17 июль 2016, в 16:22

Поделиться

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

the10thplanet
05 авг. 2014, в 00:57

Поделиться

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

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

zipzit
27 сен. 2013, в 11:01

Поделиться

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

cs075
19 окт. 2015, в 07:27

Поделиться

Ещё вопросы

  • 0Jquery добавление дополнительных # к объектам DOM
  • 1Как получить продолжительность потокового аудио с серверов онлайн
  • 0Получить данные из внешнего XML-файла, используя PHP
  • 0Проверка правильности ввода C ++
  • 1связанный список, добавляющий элемент в конец списка
  • 1как перезапустить убитое андроид приложение при тестировании с robotium
  • 1Android LunarLander и JetBoy Thread source
  • 0Google Maps Infobox, способный отображать JQuery UI Widgets
  • 0как добавить комментарии в строку таблицы в PHP
  • 0MVC TextBoxFor (model => model [i] .prop) внутри JavaScript для цикла
  • 0Понимание, почему получена ошибка «результат не определен»
  • 0Как отправить мастер смарт-формы, прежде чем перейти к последнему шагу
  • 0Как перенаправить страницу в iframe с помощью jQuery
  • 0Отправить текстовый файл по электронной почте в формате HTML
  • 1Отсутствует @using при просмотре бритвы
  • 1Javascript — выражение eval () `{}`
  • 1Как проверить, имеют ли два JButton один и тот же ImageIcon?
  • 1Удаление всевозможных лишних пробелов между предложением и абзацем
  • 0Преобразование слайдера jQuery Mobile в слайдер пользовательского интерфейса jQuery и изменение содержимого
  • 1wpf привязка пользовательского элемента управления загруженное событие не выполнено
  • 1Доступ к переменной NodeJS?
  • 0Угловой JS: «это» внутри функции нг-если
  • 0как остановить css hover с условным
  • 1Как создать правило сонара для анализа пользовательского файла XML в Java?
  • 0Функция почты не работает с опросом
  • 0Как мне создать уникальный идентификатор, который не является инкрементным?
  • 1Перемещение файлов на SDcard на Android
  • 0Бесконечная прокрутка перестает работать, как только я добавляю функцию ImagesLoaded в начальное состояние масонства
  • 0Получить приложение для входа в систему, MFC
  • 1Изображение не отображается должным образом
  • 1обратный вызов службы Android
  • 0C ++ «врезается» в виртуальные функции базовых классов
  • 1Android: запуск программной панели в пользовательском тексте редактирования
  • 0Как использовать сохраненные переменные, сохраненные в файле Javascript после перехода на новую страницу HTML?
  • 0$ scope не обновляется
  • 1Как определить, какой JList среди двух имеет фокус курсора в Java Swing?
  • 1RuntimeError: потоки могут быть запущены только один раз, когда веб-сервер Python Tkinter
  • 1Как очистить старые вкладки и добавить новую вкладку на вкладке
  • 0Вывод файлов из папки
  • 0boost :: multi_index_container — равные значения
  • 1struts2 Как прочитать значение итератора из JSP для действий
  • 0Получить все значения из одного столбца в MySQL PDO
  • 0Предварительная загрузка CSS перед HTML
  • 0Меню jquery имеет белую рамку / фон. Как это покрасить?
  • 0ИЛИ условие в регулярном выражении
  • 0Два «равных» объекта JavaScript не равны
  • 0HTML / CSS: границы по умолчанию iframe
  • 0Плавающая и ширина 100%
  • 0OpenCV проект не компилируется
  • 1Пользовательское позиционирование заголовка

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 😉


Error Description:

Error 1046 No database Selected, how to resolve ?

 Mysql no Database selected

Learn SQL — SQL tutorial — Mysql no Database selected — SQL examples — SQL programs

Solution 1:

  • We must tell the database name to mysql which one is used before created the table.
  • If the database not exist within mysql then we need to create it.
CREATE DATABASE database_name;
  • And then use the database.

Solution 2:

  • Alternately to use we can select the database using the command:
 mysql -u example_user -p --database=work < ./work.sql

Solution 3:

  • If we uses Mysql workbench then use the database:
    • On the left pane of the welcome window have Object Browser which contains default database/catalog
    • Within the drop down list we select a database .
    • And Click the «Manage Connections» options under the SQL Development heading of the Workbench splash screen to use the database.

Solution 4:

  • If we have the sql database file then we import the database in phpMyAdmin to solve this error.

Import Database in phpMyAdmin

  • Assuming that you already Created a new MySQL Database on Live Site.
  • Goto phpMyAdmin on live site — login to the database you just created.
  • And select your database from the list on the left of the page.

 How to Import Database in Mysql

Learn SQL — SQL tutorial — How to Import Database in Mysql — SQL examples — SQL programs

  • Click the «import» option on the top bar.
  • Click on the «Browse» button next to «Location of the sql file.».
  • Browse to your local SQL file and click «Open». If it is a zipped file, please unzip the file first.
  • Then choose the format «SQL»
  • Click the «Go» button at the bottom. Wait while your database imports. Depending on the size, this can take a few minutes.

 Mysql Import Database

Learn SQL — SQL tutorial — Mysql Import Database — SQL examples — SQL programs

  • Note: Before importing we must create the database which contain the same name as in the file.

Solution 5:

  • We try to import a database only after creating it.
    • If we using the mysql phpmyadmin now on the top bar we have database option to click and create a database
    • And Use the database by usual command: use database_name

UP NEXT IN SQL

  • SQL Tutorial
  • SQL Interview Questions and Answers
  • SQL HR Interview Questions and Answers
  • SQL Sample Resume
  • SQL Interview Dress Code
  • SQL Job Apply Letters
  • SQL Forums


Ошибка SQL-запроса:


MySQL сказал:


здесь нужна помощь.

  • 7 Если кому-то интересно, вы также можете указать имя базы данных с помощью команды CLI, не редактируя файл импорта.
  • то, что случилось со мной, было: создать схему, заполнить имя базы данных, затем она говорит «сбой, база данных не выбрана». повторно открываю верстак, я вижу базу данных, которую я только что не смог создать. Затем я выбираю базу данных, которую я только что создал, и открываю файл .sql и запускаю его с операторами create database и use database, он снова жалуется: «Ошибка не выбрана база данных». повторно открыть верстак, все столы построены. Система MAC, верстак 6.3.3

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


перед созданием таблицы.

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


с последующим:


  • 8 В моем случае я использовал mysqldump для экспорта базы данных и столкнулся с ней при импорте. Мне просто нужно было отредактировать экспортированный файл sql, чтобы добавить эти две команды вверху.
  • Спасибо! Это то, что мне было нужно. У меня был сценарий для создания моей базы данных и таблиц, но таблицы не создавались, потому что мне нужно было вставить команду .
  • 1 Запись: Это работает независимо от того, создана база данных или нет.

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


  • 7 Почему вместо ?

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

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

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

3- Попробуйте еще раз

У меня это работает.

  • еще одно замечание — убедитесь, что строка подключения jdbc содержит имя схемы и эта схема уже создана.

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

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


Вот документация.

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

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

Дополнение

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


  • Использование MySQL Workbench: не могли бы вы предоставить изображение с расположением раскрывающегося списка?
  • Я думаю, это может относиться к более старой версии MySQL Workbench. Я только что загрузил самую последнюю версию и нигде не вижу вкладки «обозреватель объектов».
  • Похоже, вам нужно использовать команду даже в MySQL Workbench (я использую v5.2.47), если вы получаете эту ошибку. Необходимо запускать его только один раз для каждой вкладки запроса — все последующие выполнения на этой вкладке, похоже, правильно используют базу данных.
  • Привет, Итак, для WordPress sql, как мы можем «использовать» в файле SQL. Не могли бы вы прояснить это еще раз. У меня сейчас проблема.

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

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

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

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

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

Это помогло мне. Действительно надеюсь, что это поможет

  • Вы могли бы подумать, что, если бы вы еще не были в базе данных, на странице была бы опция, позволяющая выбрать один.
  • Отредактируйте файл , используя Блокнот или Блокнот ++
  • добавьте следующие 2 строки:
  • Как мы можем написать в случае файла базы данных wordpress, когда я пытаюсь импортировать с помощью MySql Workbench, но не выбираю базу данных

Для MySQL Workbench

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

  • В MySQL Workbench 8.0 вы должны выбрать схему по умолчанию для импорта в окне импорта данных.

При импорте базы данных вам необходимо сначала создать ее с тем же именем, затем выбрать ее, а затем ИМПОРТИРОВАТЬ в нее существующую базу данных.

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

  • Пожалуйста, добавьте некоторые подробности в свой ответ, объясняя свои действия.

будьте осторожны с пустыми паролями


запросит пароль и пожалуется на

проблема в том, что опция требует, чтобы между и паролем не было пробела.


решил проблему (цитаты больше не нужны).

Цитата ivan n: «При импорте базы данных вам нужно сначала создать ее с тем же именем, затем выбрать ее, а затем ИМПОРТИРОВАТЬ в нее существующую базу данных. Надеюсь, это сработает для вас!»

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

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

  • Это должен быть комментарий под ответом Ивана, чтобы он мог изменить свой ответ, включив в него ваши шаги.

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

затем создайте таблицу: CREATE TABLE tb_name (id int, name varchar (255), salary int, city varchar (255));

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

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

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

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

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

Я опаздываю думаю:] soory,

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

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

Итак, ваша команда должна выглядеть так:


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



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

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

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка 1046 dhcp сервер
  • Ошибка 1045 приора эур