Ошибка no database selected как исправить

Error SQL query: -- -- Database: `work` -- -- -------------------------------------------------------- -- -- Table structure for table `administrators` -- CREATE TABLE IF NOT EXISTS `administrato...

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 badges517 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 badges527 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.6k16 gold badges130 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 badges517 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.8k22 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 badges29 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

32k14 gold badges103 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

9261 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

91713 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

7556 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,5584 gold badges32 silver badges59 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

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. How to fix no database selected MySQL error
  2. Level up your programming skills
  3. About
  4. [FIX] MySQL ERROR 1046 (3D000) No Database Selected
  5. Why you are getting MySQL Error 1046 (3D000) No database selected?
  6. Steps to resolve MySQL ERROR 1046 (3D000) No Database Selected:
  7. Step 1:
  8. Step 2: Select the database
  9. Step 3: Execute statement
  10. Conclusion:
  11. [Solved-5 Solutions] Error 1046 No database Selected, how to resolve ? — sql
  12. Error Description:
  13. Solution 1:
  14. Solution 2:
  15. Read Also
  16. Solution 3:
  17. Solution 4:
  18. Import Database in phpMyAdmin
  19. Форум пользователей MySQL
  20. #1 19.06.2015 21:39:50
  21. #1046 — No database selected
  22. #2 19.06.2015 22:58:49
  23. Re: #1046 — No database selected
  24. #3 19.06.2015 22:59:26
  25. Re: #1046 — No database selected
  26. #4 20.06.2015 00:05:10
  27. Re: #1046 — No database selected
  28. #5 20.06.2015 00:12:02
  29. Re: #1046 — No database selected
  30. #6 20.06.2015 00:15:26
  31. Re: #1046 — No database selected
  32. #7 22.06.2015 12:04:29
  33. Re: #1046 — No database selected
  34. У меня на mysql такая ошибка #1046 — No database selected

How to fix no database selected MySQL error

Posted on Dec 02, 2021

Learn how to resolve no database selected MySQL error

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:

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:

Next, issue the USE command as shown below:

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:

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

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:

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 😉

Level up your programming skills

I’m sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Nathan Sebhastian is a software engineer with a passion for writing tech tutorials.
Learn JavaScript and other web development technology concepts through easy-to-understand explanations written in plain English.

Источник

[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.

Источник

[Solved-5 Solutions] Error 1046 No database Selected, how to resolve ? — sql

Error Description:

Error 1046 No database Selected, how to resolve ?

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.

Solution 2:

  • Alternately to use we can select the database using the command:

Read Also

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.

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.

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

Источник

Форум пользователей MySQL

Задавайте вопросы, мы ответим

Страниц: 1 2

#1 19.06.2015 21:39:50

#1046 — No database selected

Раньше была ошибка типа:
#1064 — You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘CREATE TABLE IF NOT EXISTS `uni1_marketally` ( `id` int(11) unsigned NOT NULL ‘ at line 21

При попытке загрузить файл весом примерно 1.7мб на локалхосте выдает такую ошибку. Не знаю что делать, помогите новичку, пожалуйста!

#2 19.06.2015 22:58:49

Re: #1046 — No database selected

1. нужно указать базу, в которой создается таблица.

например, это можно указать в начале дампа с помощью команд create database или use
каким именно способом вы пытаетесь загрузить дамп?

2. по 1064
у вас в файле идет синтаксическая ошибка перед CREATE TABLE IF NOT EXISTS `uni1_marketally`
что расположено до этой команды?

#3 19.06.2015 22:59:26

Re: #1046 — No database selected

Поставьте точку с запятой перед вторым CREATE TABLE и в самом конце второго CREATE TABLE.

#4 20.06.2015 00:05:10

Re: #1046 — No database selected

1. нужно указать базу, в которой создается таблица.
например, это можно указать в начале дампа с помощью команд create database или use
каким именно способом вы пытаетесь загрузить дамп?

Писал create database `name` но не помогло.

2. по 1064 у вас в файле идет синтаксическая ошибка перед CREATE TABLE IF NOT EXISTS `uni1_marketally`
что расположено до этой команды?

Там нечего нету. Весь код я выложил на страницу.

Поставьте точку с запятой перед вторым CREATE TABLE и в самом конце второго CREATE TABLE.

Ставил, не помогает, хотя может я не туда поставил. но я пробовал по разному — не помогает

#5 20.06.2015 00:12:02

Re: #1046 — No database selected

Будет ли ошибка для такого кода? (не забудьте заменить database_name на имя вашей базы данных)

#6 20.06.2015 00:15:26

Re: #1046 — No database selected

Импорт успешно завершен, запросов выполнено: 3.
Благодарю!!

#7 22.06.2015 12:04:29

Re: #1046 — No database selected

Появилась еще одна ошибка, но на другом двиге.

USER ERROR
Message: SQL Error: No database selected

Query Code: SELECT * FROM uni1_config;
File: /includes/classes/class.Database.php
Line: 80
URL: http://test23.com/
PHP-Version: 5.2.12
PHP-API: apache2handler
MySQL-Cleint-Version: 5.0.51a
2Moons Version: UNKNOWN
Debug Backtrace:
#0 /includes/classes/Config.class.php(37): Database->query(‘SELECT * FROM u. ‘)
#1 /includes/common.php(105): Config::init()
#2 /index.php(35): require(‘FILEPATH . ‘)
#3

залил двиг, зашел в phpmyadmin и создал БД с пользователем, которому выставил все привелегии. А дальше вот такая вот ошибка. Что это означает? Не пришита БД к двигу?

Источник

У меня на mysql такая ошибка #1046 — No database selected

— —Database: `Меняйте на свой` //pAWarns and pLWarns — удаляйте — ———————————————————— —Table structure for table `accounts` — CREATE TABLE IF NOT EXISTS `accounts` ( `pID` int(11) NOT NULL AUTO_INCREMENT, `pKey` varchar(64) NOT NULL, `Name` varchar(64) NOT NULL, `pLevel` int(11) NOT NULL, `pPhousekey` int(11) NOT NULL, `pPbiskey` int(11) NOT NULL, `pPsbiskey` int(11) NOT NULL, `pAdmInections` int(11) NOT NULL, `pAdmInectionsVaip` int(11) NOT NULL, `pAWarns` int(11) NOT NULL, `pLWarns` int(11) NOT NULL, `pFuelcar` float NOT NULL, `pHeadValue` int(11) NOT NULL, `pContract` int(11) NOT NULL, `pCar` int(11) NOT NULL, `pHelper` int(11) NOT NULL, `pDMInections` int(11) NOT NULL, `pDRInections` int(11) NOT NULL, `pDRInectionsTime` int(11) NOT NULL, `pReg` int(11) NOT NULL, `pResh` int(11) NOT NULL, `pYint` int(11) NOT NULL, `pSum` int(11) NOT NULL, `pSex` int(11) NOT NU[. ]


— Структура таблицы `accounts`

CREATE TABLE IF NOT EXISTS `accounts` (
`pID` int(11) NOT NULL AUTO_INCREMENT,
`password` varchar(65) NOT NULL,
`salt` varchar(10) NOT NULL,
`Name` varchar(64) NOT NULL,
`pLevel` int(11) NOT NULL,
`pPhousekey` int(11) NOT NULL,
`pAlcoInvenxua` int(11) NOT NULL,
`pFuelcar` int(11) NOT NULL,
`pHeadValue` int(11) NOT NULL,
`pContract` int(11) NOT NULL,
`pCar` int(11) NOT NULL DEFAULT ‘462’,
`pCar2` int(11) NOT NULL DEFAULT ‘462’,
`pHelper` int(11) NOT NULL,
`pDonatemoney2` int(11) NOT NULL,
`pDonateRank` int(11) NOT NULL,
`pDonateRankTime` int(11) NOT NULL,
`pSex` int(11) NOT NULL,
`pMuted` int(11) NOT NULL,
`pExp` int(11) NOT NULL,
`pCash` int(11) NOT NULL,
`pKills` int(11) NOT NULL,
`pJailed` int(11) NOT NULL,
`pJailTime` int(11) NOT NULL,
`pMats` int(11) NOT NULL,
`pHeal` int(11) NOT NULL,
`pLeader` int(11[. ]
Ответ MySQL: Документация

#1046 — База данных не выбрана
Помогите

Источник

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

Поделиться

Ещё вопросы

  • 1Выравнивание TextBlock по вертикали внутри StackPanel
  • 1Как отформатировать код Java в редакторе Ace
  • 1chrome.runtime.onMessage.addListener не определен в скрипте содержимого
  • 0Выделение переменного количества объектов в стеке в C ++
  • 0Что я делаю неправильно, загружая этот массив JS?
  • 1Как изменить цвет фона JFrame [дубликата]
  • 1Matplotlib: Как рисовать линии краев в Arc — патчи
  • 1C # Многомерная разница между установкой значения
  • 1Как сохранить изображение, загруженное через url, в базу данных sqlite в двоичном формате
  • 0Перезапись URL с использованием include не загружает таблицу стилей
  • 0blueimp jQuery-File-Upload не работает
  • 1Python — Как напечатать содержимое списка, в котором есть объекты класса?
  • 0Счетчик JavaScript не работает
  • 1Как я могу отключить спекулятивное выполнение Hadoop из Java
  • 1Как вытащить строки из массива, адаптированного списка для кликаемого элемента списка
  • 1производительность и объем памяти функций стрелок
  • 0AngularJS — снятие флажка
  • 0GROUP BY одна и та же запись, но разные TIMESTAMP / DATETIME
  • 1Как получить доступ к динамическому ключу в массиве объектов
  • 0ActiveRecord NoDatabaseError при попытке подключиться к экземпляру AWS MySQL
  • 1Как удалить каждую строку, имеющую все столбцы, равную None для фрейма данных
  • 0Контейнер — это необъектная ошибка в фикстурах данных Symfony
  • 0Не удалось разрешить «state1» из состояния «state» при наличии параметров в URL-ссылке
  • 1Как заполнить значения Java-объекта в JSP
  • 0создание шаблона конструктора шаблонного класса
  • 0Перенаправить из .net aspx в html
  • 0алгоритмическая сложность следующего фрагмента кода
  • 0Если идентификатор существует в массиве JavaScript с Angularjs
  • 0Веб-приложение Angular: заставка не отображается, а браузер занят загрузкой файлов js
  • 0Прокрутите массив php и вставьте ключ => значение в указанной позиции
  • 0C ++ Tron Player Lightcycle двигаться в одном направлении
  • 0Проверить, что все раскрывающиеся значения отличаются друг от друга с помощью Javascript и / или Jquery?
  • 0symfony2 doctrine2 не сбрасывает новую сущность
  • 0Передача ассоциативного массива javascript-php в массив недельных календарей
  • 0индекс текущего выбранного элемента в массиве
  • 0Не могу установить zfc-user с zfc-user-doctrine-mongo-odm
  • 0Супервизор работает в фоновом режиме, но задания сразу становятся неудачными
  • 1Как обрабатывать события входящих звонков в Android
  • 1getCurrentPosition lat / lng не переводит на правильную позицию в Google Maps
  • 1Получение идентификатора программно сгенерированной сетки кнопок в Android
  • 1Ошибка панд. Почему мои объекты смешанного типа?
  • 1Идентификация неофициальных устройств Android
  • 1Custom Keras Loss (который НЕ имеет форму f (y_true, y_pred))
  • 0Qt, перечисления и компилятор метаобъектов
  • 0Встроенный список с отступом
  • 0PHP массив из функции
  • 1Здравствуйте, Google Maps Пример NULL Указатель Исключение
  • 0Сравните две даты в умнице
  • 0JQuery спрайт анимация переключения без плагина
  • 1Получить позицию прокрутки в виде списка

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

Stuck with “No Database selected” error during the SQL file import? Our Support Engineers are here with an easy solution.

At Bobcares, we offer solutions to problems like these as a part of our Server Management Services. Let’s find out what our Support Team recommends when faced with “No Database selected” error during the SQL file import.

Resolving “No Database selected” error during the SQL file import

As the error name suggests, the reason behind the error is not selecting a database before importing the SQL file. Our Support Engineers offer five different ways to resolve this error. Let’s take a look at each of these solutions.

Solution 1

  1. First, use the command below to mention the name of the database before creating the table:
     USE database_name;
  2. In case, the database does not exist, create a new one with the command below:
    CREATE DATABASE database_name;

    Then use the database with the command mentioned in the previous step.

Solution 2
You can also select the database to be used with the following command:

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

Solution 3
If you are using MySQL workbench, our Support Engineers recommend these steps:

  1. First, navigate to the welcome window’s left pane and go to Object Browser.
  2. Then, select a database from the drop-down list.
  3. After that, navigate to SQL Development in the Workbench splash screen and click Manage Connections.

Solution 4
If you have an SQL database file, you can also import it to PhpMyAdmin and resolve the “No Database selected” error during the SQL file import as seen below:

  1. First, ensure that you already have a new MySQL database on Live Site.
  2. After that, go to phpMyAdmin on the live site and log in to the database.
  3. Next, select the database from the list.
  4. Then, click Import from the top bar.
  5. After that, click the Browse button located near the
  6. Then, browse and locate the local SQL file and click Open. Remember to unzip of first if it is a zipped file.
  7. Next, choose SQL as the format and click Go.
  8. You will have to wait for a few minutes, depending on the size of the database.

Our Support Engineers would like to remind you that the created database needs to have the same name as mentioned in the file.

Solution 5
This solution involves importing the database only after creating it.

  1. First, use MySQL phpMyAdmin and create a new database.
  2. Then, use the database by running the following command:
    use database_name

[ Require assistance? Try our Server Management Services.]

Conclusion

At the end of the day, the Support Engineers introduced five different ways to resolve “No Database selected” error during the SQL file import with ease.

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.

GET STARTED

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Ошибка no bootable device на ноутбуке acer что делать
  • Ошибка od off хендай акцент
  • Ошибка no bootable device is detected system will enter the bios setup utility как исправить
  • Ошибка ocf на частотнике
  • Ошибка no boot filename received

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

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