在本章中,我们将学习如何创建表。 在创建表之前,首先确定其名称,字段名称和字段定义。
以下是表创建的一般语法:
create table table_name (column_name column_type);
查看在products数据库中创建表所使用的命令 -
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字段。 关键字主键将列定义为主键。 多个列以逗号分隔可以定义主键。
创建表的两个主要方法是使用命令提示符和php脚本。
使用create table命令执行任务,如下所示 -
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 | +------------------------+
确保所有命令都以分号结尾。
php为表创建提供mysql_query()。 它的第二个参数包含必要的sql命令 -
<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
";
mysql_close($conn);
?>
</body>
</html>
在成功创建表,你会看到下面的输出 -
mysql> table created successfully