Fixing the "Error 1046: No database selected" MySQL Issue
This common MySQL error arises when you try to run an SQL command without specifying the target database. Before executing any SQL query, you must select the database using the USE
command.
For example, this CREATE TABLE
statement:
<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>
will fail with "Error 1046: No database selected" if a database isn't already chosen.
Solution:
The solution is simple: select your database before running your query. Use the following syntax:
<code class="language-sql">USE `database_name`;</code>
Replace database_name
with the actual name of your database.
Database Doesn't Exist?
If the database doesn't yet exist, create it first using CREATE DATABASE
, then select it with USE
:
<code class="language-sql">CREATE DATABASE `database_name`; USE `database_name`;</code>
After successfully selecting the database, your SQL queries will execute correctly.
The above is the detailed content of How to Fix 'Error 1046 No database selected' in MySQL?. For more information, please follow other related articles on the PHP Chinese website!