i’m having trubble in executing an SQL command with in intellij idea with hibernate.
this is the code i wrote:
import models.Employee;
import org.hibernate.ejb.HibernatePersistence;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.spi.PersistenceProvider;
import java.util.HashMap;
import java.util.List;
public class manager {
public final static String SELECT_QUERY = new String("from Employee where id =:id");
public static void main(String[] args){
int id = 21577911;
PersistenceProvider pp = new HibernatePersistence();
EntityManagerFactory emf = pp.createEntityManagerFactory("NewPersistenceUnit", new HashMap());
EntityManager em = emf.createEntityManager();
List<Employee> employees = em.createQuery(SELECT_QUERY, Employee.class).setParameter("id", id).getResultList();
System.out.println(employees);
em.close();
}
}
and these are the errors:
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not extract ResultSet
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1387)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1310)
at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:273)
at manager.main(manager.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: org.hibernate.exception.GenericJDBCException: could not extract ResultSet
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:61)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2036)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1836)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1815)
at org.hibernate.loader.Loader.doQuery(Loader.java:899)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:341)
at org.hibernate.loader.Loader.doList(Loader.java:2522)
at org.hibernate.loader.Loader.doList(Loader.java:2508)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2338)
at org.hibernate.loader.Loader.list(Loader.java:2333)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:490)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:355)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1269)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:264)
... 6 more
Caused by: java.sql.SQLException: **No database selected**
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2734)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2322)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:56)
... 21 more
i have configured the persistence.xml exactly as in the video demo in:
http://www.jetbrains.com/idea/features/jpa_hibernate.html
Mike Cole
14.2k26 gold badges113 silver badges191 bronze badges
asked May 15, 2013 at 13:26
Apparently this occurs when your application does not know what database to use. to resolve this issue, you should change your database driver url from:
"URL"="jdbc:mysql://localhost:3306/"
to
"URL"="jdbc:mysql://localhost:3306/databasename"
Java Devil
10.5k7 gold badges32 silver badges48 bronze badges
answered Jul 21, 2013 at 23:53
WilliamsWilliams
1511 silver badge3 bronze badges
I am using hibernate in EJBs
and exception occurred in glassfish
SQL Error: 1046, SQLState: 3D000
No database selected
i did checked in glassfish JDBC connection pool additional propteries
URL and url property was set like this
jdbc:mysql://localhost:3306/
fix is just added database name in url and URL property
jdbc:mysql://localhost:3306/{databasename}
and it worked f
error was
answered Apr 13, 2020 at 8:53
Having problems with the database configuration and XML mapping configurations.
Oct 29, 2016 2:02:36 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Oct 29, 2016 2:02:36 PM org.hibernate.dialect.Dialect
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Hibernate: /* insert com.navid.practice.hibernate.User */ insert into USERS (NAME, TOTAL, ID) values (?, ?, ?)
Oct 29, 2016 2:02:36 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1046, SQLState: 3D000
Oct 29, 2016 2:02:36 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: No database selected
Oct 29, 2016 2:02:36 PM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
Oct 29, 2016 2:02:36 PM org.hibernate.internal.ExceptionMapperStandardImpl mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [org.hibernate.exception.GenericJDBCException: could not execute statement]
javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not execute statement
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:147)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1412)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:476)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3165)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2379)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:146)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:220)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
at com.navid.practice.hibernate.Program.main(Program.java:26)
Caused by: org.hibernate.exception.GenericJDBCException: could not execute statement
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207)
at org.hibernate.engine
the issue was resolved by changing the highelighed part to the proper part according to the database configuration.
<hibernate-mapping> <class name="com.navid.practice.hibernate.User" table="USERS"> <id name="id" type="int"> <column name="ID" /> <generator class="assigned" /> </id> <property name="name" type="java.lang.String"> <column name="NAME" /> </property> <property name="total" type="int"> <column name="TOTAL" /> </property> </class> </hibernate-mapping>
Solution:
in database side, that table’s field = ID, was configuration as auto increment so I change that highlighted line to identity.
<generator class="identity" />
Published by Navid’s Thoughts
Just an enthusiast about Programming and Gaming …
View all posts by Navid’s Thoughts
Published
October 29, 2016October 29, 2016
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 <database_name>;
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>;
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.
Cheers !!!
Similar article:
1. Fix “unknown collation ‘utf8mb4_unicode_520_ci’” Error
у меня проблемы с выполнением команды SQL с идеей intellij с спящим режимом. это код, который я написал:
import models.Employee;
import org.hibernate.ejb.HibernatePersistence;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.spi.PersistenceProvider;
import java.util.HashMap;
import java.util.List;
public class manager {
public final static String SELECT_QUERY = new String("from Employee where id =:id");
public static void main(String[] args){
int id = 21577911;
PersistenceProvider pp = new HibernatePersistence();
EntityManagerFactory emf = pp.createEntityManagerFactory("NewPersistenceUnit", new HashMap());
EntityManager em = emf.createEntityManager();
List<Employee> employees = em.createQuery(SELECT_QUERY, Employee.class).setParameter("id", id).getResultList();
System.out.println(employees);
em.close();
}
}
и это ошибки:
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not extract ResultSet
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1387)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1310)
at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:273)
at manager.main(manager.java:31)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: org.hibernate.exception.GenericJDBCException: could not extract ResultSet
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:61)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2036)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1836)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1815)
at org.hibernate.loader.Loader.doQuery(Loader.java:899)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:341)
at org.hibernate.loader.Loader.doList(Loader.java:2522)
at org.hibernate.loader.Loader.doList(Loader.java:2508)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2338)
at org.hibernate.loader.Loader.list(Loader.java:2333)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:490)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:355)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1269)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:264)
... 6 more
Caused by: java.sql.SQLException: **No database selected**
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2734)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2322)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:56)
... 21 more
я настроил файл persistence.xml точно так же, как в демо-видео:
http://www.jetbrains.com/idea/features/jpa_hibernate.html
2 ответы
По-видимому, это происходит, когда ваше приложение не знает, какую базу данных использовать. чтобы решить эту проблему, вы должны изменить URL-адрес драйвера базы данных с:
"URL"="jdbc:mysql://localhost:3306/"
в
"URL"="jdbc:mysql://localhost:3306/databasename"
Создан 22 июля ’13, 01:07
Я использую спящий режим в EJB, и в стеклянной рыбе произошло исключение.
SQL Error: 1046, SQLState: 3D000
No database selected
я проверил в пуле соединений JDBC Glassfish дополнительные свойства URL-адреса, и свойство url было установлено следующим образом
jdbc:mysql://localhost:3306/
исправление — это просто добавленное имя базы данных в URL-адрес и свойство URL-адреса
jdbc:mysql://localhost:3306/{databasename}
и это сработало, ошибка была
ответ дан 13 апр.
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками
intellij-idea
nhibernate-mapping
or задайте свой вопрос.
MySQL 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.
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.
First, we have shown you how to import files correctly, and second, we have given you tips on how to solve the error 1046 when it occurs. These fixes are pretty straightforward, so why can’t you start applying them today?
- Author
- Recent Posts
Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.
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 😉