Home > Database > Mysql Tutorial > How to Fix 'Error 1046 No database selected' in MySQL?

How to Fix 'Error 1046 No database selected' in MySQL?

Mary-Kate Olsen
Release: 2025-01-17 18:46:11
Original
691 people have browsed it

How to Fix

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template