Sql 简明教程

SQL - SELECT Database, USE Statement

要在 SQL 中使用数据库,我们需要首先选择要使用的数据库。选择数据库后,我们可以对其执行各种操作,例如创建表、插入数据、更新数据和删除数据。

To work with a database in SQL, we need to first select the database we want to work with. After selecting the database, we can perform various operations on it such as creating tables, inserting data, updating data, and deleting data.

The USE DATABASE Statement

SQL USE DATABASE 语句用于从系统中可用的数据库列表中选择一个数据库。选择数据库后,我们可以对其执行各种操作,例如 creating tablesinserting data 、更新数据和 deleting data

The SQL USE DATABASE statement is used to select a database from a list of databases available in the system. Once a database is selected, we can perform various operations on it such as creating tables, inserting data, updating data, and deleting data.

Syntax

以下是 SQL 中 USE DATABASE 语句的语法:

Following is the syntax of the USE DATABASE statement in SQL −

USE DatabaseName;

此处, DatabaseName 是我们要选择的数据库的名称。数据库名称在 RDBMS 中始终是唯一的。

Here, the DatabaseName is the name of the database that we want to select. The database name is always unique within the RDBMS.

Example

首先,我们将使用以下 SQL CREATE DATABASE 查询创建一个数据库:

First of all we will create a database using the following SQL CREATE DATABASE query −

CREATE DATABASE testDB;

现在,我们可以按如下方式列出所有可用数据库:

Now, we can list all the available databases as follws −

SHOW DATABASES;

输出将显示为:

The output will be displayed as −

Database

master

performance_schema

information_schema

mysql

testDB

Example: Select/Switch Database

以下查询用于将当前数据库选择/切换到 testDB

Following query is used to select/switch the current database to testDB

USE testDB;
Database changed

一旦我们完成切换到数据库 testDB ,就可以执行操作,例如创建表和在该表中插入数据,如下所示:

Once we finish switching to the database testDB we can perform operations such as creating a table, and inserting data in that table as shown below −.

CREATE TABLE CALENDAR(MONTHS DATE NOT NULL);

现在,让我们使用 SQL INSERT 语句在 CALENDAR 表中插入一些记录,如下面的查询所示:

Now, let us insert some records in the CALENDAR table using SQL INSERT statements as shown in the query below −

INSERT INTO CALENDAR(MONTHS) VALUES('2023-01-01');
INSERT INTO CALENDAR(MONTHS) VALUES('2023-02-01');
INSERT INTO CALENDAR(MONTHS) VALUES('2023-03-01');
INSERT INTO CALENDAR(MONTHS) VALUES('2023-04-01');
INSERT INTO CALENDAR(MONTHS) VALUES('2023-12-01');

让我们使用 SQL SELECT 语句列出 CALENDAR 表中的所有记录来验证操作,如下所示:

Let’s verify the operation by listing all the records from CALENDAR table using SQL SELECT statement as shown below −

SELECT * FROM CALENDAR;

输出将显示为:

The output will be displayed as −

MONTHS

2023-01-01

2023-02-01

2023-03-01

2023-04-01

2023-12-01

Selecting a Non Existing Database

尝试选择一个不存在的数据库将导致错误。在以下查询中,我们尝试切换到不存在的数据库:

An attempt to select a non-existent database will result in an error. In the following query we are trying to switch to the database which does not exist −

Example

USE unknownDatabase;

Output

执行上述查询时,将显示输出为:

On executing the above query, the output will be displayed as −

ERROR 1049 (42000): Unknown database 'unknownDatabase'