Mariadb 简明教程

MariaDB - Select Database

连接到 MariaDB 后,您必须选择一个数据库以供使用,因为可能存在多个数据库。有两种方法可以执行此任务:从命令提示符或通过 PHP 脚本。

After connecting to MariaDB, you must select a database to work with because many databases may exist. There are two ways to perform this task: from the command prompt or through a PHP script.

The Command Prompt

要从命令提示符选择一个数据库,只需使用 SQL 命令 ‘use’

In choosing a database at the command prompt, simply utilize the SQL command ‘use’

[root@host]# mysql -u root -p

Enter password:******

mysql> use PRODUCTS;

Database changed

mysql> SELECT database();
+-------------------------+
| Database                |
+-------------------------+
| PRODUCTS                |
+-------------------------+

选择数据库后,所有后续命令都将在所选数据库上操作。

Once you select a database, all subsequent commands will operate on the chosen database.

Note − 所有名称(例如,数据库、表、字段)都区分大小写。确保命令符合正确的格式。

Note − All names (e.g., database, table, fields) are case sensitive. Ensure commands conform to the proper case.

PHP Select Database Script

PHP 提供 mysql_select_db 函数来进行数据库选择。该函数使用两个参数,一个可选参数,并在成功选择时返回 “true” 值,在失败时返回 “false” 值。

PHP provides the mysql_select_db function for database selection. The function uses two parameters, one optional, and returns a value of “true” on successful selection, or false on failure.

Syntax

查看以下选择数据库脚本语法。

Review the following select database script syntax.

bool mysql_select_db( db_name, connection );

参数说明如下 −

The description of the parameters is given below −

S.No

Parameter & Description

1

db_name This required parameter specifies the name of the database to use.

2

connection When not specified, this optional parameter uses the most recent connection used.

尝试以下示例代码来选择一个数据库 −

Try the following example code for selecting a database −

<html>
   <head>
      <title>Select a MariaDB Database</title>
   </head>

   <body>
      <?php
         $dbhost = 'localhost:3036';
         $dbuser = 'guest1';
         $dbpass = 'guest1a';
         $conn = mysql_connect($dbhost, $dbuser, $dbpass);

         if(! $conn ) {
            die('Could not connect: ' . mysql_error());
         }
         echo 'Connected successfully';

         mysql_select_db( 'PRODUCTS' );
         mysql_close($conn);
      ?>
   </body>
</html>

成功选择后,您将看到以下输出 −

On successful selection, you will see the following output −

mysql> Connected successfully