Mariadb 简明教程
MariaDB - Create Tables
在本教程中,我们将学习如何创建表。在创建表之前,首先要确定其名称、字段名和字段定义。
In this chapter, we will learn how to create tables. Before creating a table, first determine its name, field names, and field definitions.
以下是一般创建表语法:
Following is the general syntax for table creation −
CREATE TABLE table_name (column_name column_type);
查看用于在 PRODUCTS 数据库中创建表的命令:
Review the command applied to creating a table in the PRODUCTS database −
databaseproducts_ tbl(
product_id INT NOT NULL AUTO_INCREMENT,
product_name VARCHAR(100) NOT NULL,
product_manufacturer VARCHAR(40) NOT NULL,
submission_date DATE,
PRIMARY KEY ( product_id )
);
上述示例使用“NOT NULL”作为字段属性,以避免因空值引起的错误。属性“AUTO_INCREMENT”指示 MariaDB 将下一个可用值添加到 ID 字段。关键字 primary key 定义列为 primary key 。多个以逗号分隔的列可以定义一个主键。
The above example uses “NOT NULL” as a field attribute to avoid errors caused by a null value. The attribute “AUTO_INCREMENT” instructs MariaDB to add the next available value to the ID field. The keyword primary key defines a column as the primary key. Multiple columns separated by commas can define a primary key.
创建表的两种主要方法是使用命令提示符和 PHP 脚本。
The two main methods for creating tables are using the command prompt and a PHP script.
The Command Prompt
使用 CREATE TABLE 命令执行任务,如下所示:
Utilize the CREATE TABLE command to perform the task as shown below −
root@host# mysql -u root -p
Enter password:*******
mysql> use PRODUCTS;
Database changed
mysql> CREATE TABLE products_tbl(
-> product_id INT NOT NULL AUTO_INCREMENT,
-> product_name VARCHAR(100) NOT NULL,
-> product_manufacturer VARCHAR(40) NOT NULL,
-> submission_date DATE,
-> PRIMARY KEY ( product_id )
-> );
mysql> SHOW TABLES;
+------------------------+
| PRODUCTS |
+------------------------+
| products_tbl |
+------------------------+
确保用分号终止所有命令。
Ensure all commands are terminated with a semicolon.
PHP Create Table Script
PHP 提供了 mysql_query() 用于创建表。其第二个参数包含必要的 SQL 命令 −
PHP provides mysql_query() for table creation. Its second argument contains the necessary SQL command −
<html>
<head>
<title>Create a MariaDB Table</title>
</head>
<body>
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ){
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully<br />';
$sql = "CREATE TABLE products_tbl( ".
"product_id INT NOT NULL AUTO_INCREMENT, ".
"product_name VARCHAR(100) NOT NULL, ".
"product_manufacturer VARCHAR(40) NOT NULL, ".
"submission_date DATE, ".
"PRIMARY KEY ( product_id )); ";
mysql_select_db( 'PRODUCTS' );
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not create table: ' . mysql_error());
}
echo "Table created successfully\n";
mysql_close($conn);
?>
</body>
</html>
成功创建表后,您将看到以下输出 −
On successful table creation, you will see the following output −
mysql> Table created successfully