Home >Database >Mysql Tutorial >Why Am I Getting MySQL Error 1046: No Database Selected?
MySQL Error 1046: No Database Selected – A Troubleshooting Guide
Encountering MySQL error 1046 ("No database selected") during database operations (like table creation or data insertion) is a common issue. This error simply means you haven't specified which database MySQL should target for your queries.
The solution is straightforward: use the USE
statement to select your database before executing any queries.
The USE
Statement
The syntax is:
<code class="language-sql">USE database_name;</code>
Example Scenario
Let's say you're trying to create an administrators
table, but receive error 1046. First, you need to create the database (e.g., "work"):
<code class="language-sql">CREATE DATABASE work;</code>
Then, select the newly created database:
<code class="language-sql">USE work;</code>
Now, you can safely create your table:
<code class="language-sql">CREATE TABLE IF NOT EXISTS `administrators` ( `user_id` varchar(30) NOT NULL, `password` varchar(30) NOT NULL ) ENGINE = InnoDB DEFAULT CHARSET = latin1;</code>
Handling Error 1049
If the database ("work" in this case) doesn't exist before using the USE
statement, you'll encounter error 1049 ("Unknown database"). Always create the database first, then select it using USE
.
The above is the detailed content of Why Am I Getting MySQL Error 1046: No Database Selected?. For more information, please follow other related articles on the PHP Chinese website!