Home > Database > Mysql Tutorial > body text

How to create a table with mysql code

下次还敢
Release: 2024-04-05 17:09:16
Original
1248 people have browsed it

The steps to create a table using MySQL code are as follows: Connect to the database Use the CREATE TABLE statement to create the table Define the table columns and specify the data type Add constraints to enforce data integrity Execute the CREATE TABLE statement Use the SHOW TABLES statement to verify the creation of the table

How to create a table with mysql code

How to create a table using MySQL code

Creating a table is the basic step in building a MySQL database. Here is a detailed guide on how to create a table using MySQL code:

1. Connect to the database

<code class="mysql">  mysql -u 用户名 -p 密码 -h 主机名 数据库名</code>
Copy after login

2. Create table statement

CREATE TABLE statement is used to create a table. Its format is as follows:

<code class="mysql">CREATE TABLE 表名 (
  列名 数据类型 [约束],
  ...
);</code>
Copy after login

3. Column definition

The table consists of columns, and each column has a name and a data type. Common MySQL data types include:

  • Integers: INT, SMALLINT
  • Floating point numbers: FLOAT, DOUBLE
  • Strings: VARCHAR(length), CHAR(length )
  • Date and time: DATE, TIME, DATETIME

4. Constraints

Constraints can be used to enforce data integrity rules. Common constraints include:

  • NOT NULL: The column cannot be NULL
  • UNIQUE: The column value must be unique
  • PRIMARY KEY: The value of this column is unique and identifies each row

5. Example

Let us create a A table named customers that contains customer information:

<code class="mysql">CREATE TABLE customers (
  id INT NOT NULL AUTO_INCREMENT,
  name VARCHAR(255) NOT NULL,
  email VARCHAR(255) UNIQUE,
  PRIMARY KEY (id)
);</code>
Copy after login

6. Execute the statement

using a semicolon (;) End the CREATE TABLE statement and press Enter to execute it.

7. Verify the creation of the table

You can verify the creation of the table by using the SHOW TABLES statement:

<code class="mysql">SHOW TABLES;</code>
Copy after login

If customers table exists, it will be listed.

The above is the detailed content of How to create a table with mysql code. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!