MySQL Learning 1: Zero-based Additions, Deletions, Modifications and Checking Xiaobai's Simple Getting Started Tutorial (with MySQL download address)


Preface

MySQL is an open source relational database management system (RDBMS) that uses the most commonly used database management language-Structured Query Language (SQL) for database management. MySQL is open source, so anyone can download it under the General Public License and modify it according to individual needs. MySQL has attracted much attention because of its speed, reliability, and adaptability. Most people think that MySQL is the best choice for managing content when transactional processing is not required.

Insert picture description here


For more detailed introduction of MySQL commands, please move to another post of mine: MySQL Learning II: MySQL Command Encyclopedia and Summary of Common Errors

1. Introduction to related concepts of MySQL

MySQL is a relational database (Relational Database Management System) . This so-called "relational" can be understood as the concept of "tables". A relational database consists of one or several tables.

  • Header: the name of each column
  • Column (row): a collection of data with the same data type
  • Row (col): Each row is used to describe the specific information of a certain person/thing
  • Value (value): the specific information of the row, each value must be the same as the data type of the column
  • Key: The method used to identify a specific person/thing in the table, the value of the key is unique in the current column

2. MySQL configuration under Windows

Take MySQL 5.1 free installation version as an example, download mysql-noinstall-5.1.69-win32.zip official download page

2.1, MySQL configuration steps

  • Unzip the downloaded mysql-noinstall-5.1.69-win32.zip to the location to be installed, such as: C:\Program Files;
  • Find the my-small.ini configuration file in the installation folder, rename it to my.ini, open it for editing, and add a line under both [client] and [mysqld]:
default-character-set = gbk;
  • Open the Windows environment variable settings, create a new system variable name MYSQL_HOME, the variable value is the MySQL installation directory path, here is C:\Program Files\mysql-5.1.69-win32;
  • Add in the Path variable of the environment variable ;%MYSQL_HOME%\bin;;
  • To install the MySQL service, open the Windows command prompt, enter the DOS command window, enter the bin directory of the mysql installation directory, and execute the command: the mysqld --install MySQL --defaults-file="my.ini"prompt "Service successfully installed."indicates success.

note:

  1. Execute the following command in the bin directory of the installation directory of mysql: mysqld –install…….
  2. When an error occurs Install/Remove of the Service Denied, the solution: Under win7, search for cmd in the start, and
    select "Open as an administrator" when opening the cmd.exe program. Or enter C:\Windows\System32 and find cmd.exe, right-click and select "Open as Administrator".

2.2, MySQL service start, stop and uninstall

To start, stop and uninstall the MySQL service, run at the Windows command prompt:

  • start up:net start MySQL
  • stop:net stop MySQL
  • Uninstall:sc delete MySQL

Three, the basic composition of the MySQL script

Similar to conventional scripting languages, MySQL also has a set of rules for the use of characters, words, and special symbols. MySQL completes operations on the database by executing SQL scripts. The script consists of one or more MySQL statements (SQL statements + extended statements). ), the suffix of the script file is generally .sql when saving. Under the console, the MySQL client can also execute single-sentence statements without saving them as .sql files.

Identifiers : Identifiers are used to name some objects, such as databases, tables, columns, variables, etc., so that they can be referenced elsewhere in the script. MySQL identifier naming rules are a bit cumbersome. Here we use universal naming rules: identifiers consist of letters, numbers or underscores (_), and the first character must be a letter or underscore.
Whether the identifier is case sensitive depends on the current operating system. It is not sensitive under Windows, but for most linux\unix systems, the case of these identifiers is sensitive.

Keywords : MySQL has many keywords, so I won't list them one by one here. Learn by learning. These keywords have their own specific meanings, and try to avoid them as identifiers.

Statement : MySQL statement is the basic unit of MySQL script. Each statement can complete a specific operation. It is composed of SQL standard statement + MySQL extended statement.

Functions : MySQL functions are used to implement some advanced functions of database operations. These functions are roughly divided into the following categories: string functions, mathematical functions, date and time functions, search functions, encryption functions, and information functions.

Four, data types in MySQL

MySQL has three types of data types, namely numbers, dates/times, and strings. These three types are divided into many subtypes in more detail.

4.1, number type

  • 整数:tinyint、smallint、mediumint、int、bigint
  • Floating point number: float, double, real, decimal

4.2, date and time

date、time、datetime、timestamp、year

4.3, string type

  • String: char, varchar
  • Text: tinytext, text, mediumtext, longtext
  • Binary (can be used to store pictures, music, etc.): tinyblob, blob, mediumblob, longblob

Five, use MySQL database

5.1, log in to MySQL

When the MySQL service is running, we can log in to the MySQL database through the client tool that comes with MySQL. First, open the command prompt and enter the name in the following format:

mysql -h 主机名 -u 用户名 -p

Syntax description:

-h: This command is used to specify the MySQL host name that the client wants to log in. This parameter can be omitted when logging in to the current machine;: The
-uuser name to log in;:
-pTell the server that a password will be used to log in, if the user name and password to log in is empty , You can ignore this option.

Just log on to the machine installed in the MySQL database as an example, enter the command line mysql -u root -pand press Enter to confirm, if installed correctly and MySQL is running, you get the following response: Enter password:.

If the password exists, enter the password to log in. If it does not exist, press Enter to log in. According to the installation method in this article, the default root account has no password. After successful login, you will see Welecome to the MySQL monitor...the prompt of.

Then the command prompt will always mysql>add a blinking cursor to wait for the input of the command, input exitor quitlogout.

5.2, create a database

Use the create database statement to complete the creation of the database, the format of the creation command is as follows:

create database 数据库名 [其他选项];

For example: we need to create a database named samp_db, execute the following command on the command line:

create database samp_db character set gbk;

Note: In order to facilitate the display of Chinese at the command prompt, the database character code is specified as gbk through character set gbk when creating.
Creation will be successful Query OK, 1 row affected(0.02 sec)response.

Note: MySQL statement ends with a semicolon (;). If you do not add a semicolon at the end of the statement, the command prompt will prompt you to continue typing with -> (There are some special cases, but adding a semicolon is not wrong of).

Tip: You can use the show databases;command to see which databases have been created.

5.3, select the database to be operated

To operate on a database, you must first select the database, otherwise an error will be prompted:

ERROR 1046(3D000): No database selected

5.3.1, specify the use of the database when logging in to the database

The command is as follows:

mysql -D 所选择的数据库名 -h 主机名 -u 用户名 -p

For example: select the database just created when logging in:

mysql -D samp_db -u root -p

5.3.2. Use the use statement to specify after logging in

The command is as follows:

use 数据库名;

Note: The use statement does not need to add a semicolon.
For example: the implementation use samp_dbto select the database you just created, the success will be prompted to select: Database changed.

5.4, ​​create a database table

Use the create table statement to complete the creation of the table, the common form of create table:

create table 表名称(列声明);

Take the creation of the students table as an example. The table will store the student number (id), name (name), gender (sex), age (age), and telephone number (tel):

create table students(
	id int unsigned not null auto_increment primary key,
	name char(8) not null,
	sex char(4) not null,
	age tinyint unsigned not null,
	tel char(13) null default "-"
	);

Note: For some longer statements, it may be easy to make mistakes in the command prompt, so we can enter the statement through any text editor and save it in the file createtable.sql, and execute it through the file redirection under the command prompt Execute the script.

Open a command prompt and enter:mysql -D samp_db -u root -p < createtable.sql

prompt:

  1. If connecting to a remote host, please add -h command;
  2. If the createtable.sql file is not in the current working directory, you need to specify the full path of the file.

SQL statement analysis: In
create table tablename(columns)order to create a database table command, the name of the column and the data type of the column will be completed in brackets; the
contents of 5 columns are declared in the brackets , id, name, sex, age, tel are the names of each column, followed by Followed by the data type description, separated by a comma (,) between the column and column description;

To "id int unsigned not null auto_increment primary key"row description:

  • "Id" is the name of the column.
  • "Int" specifies that the type of the column is int (the value range is -8388608 to 8388607), and we will use "unsigned" to modify it later to indicate that the type is unsigned. At this time, the value range of the column is 0 To 16777215.
  • "Not null" means that the value of this column cannot be empty and must be filled in. If this attribute is not specified, it can be empty by default.
  • "Auto_increment" needs to be used in an integer column. If the column is NULL when inserting data, MySQL will automatically generate a unique identifier value larger than the existing value. There can be only one such value in each table and the column must be an index column.
  • "Primary key" means that this column is the primary key of the table, the value of this column must be unique, and MySQL will automatically index this column.
  • The following char(8) indicates that the length of the stored character is 8, the value of tinyint ranges from -127 to 128, and the default attribute specifies the default value when the column value is empty.

prompt:

  1. Use show tables;command to see the name of the table has been created;
  2. Use describe 表名;the command to view detailed information tables have been created.

Six, operate MySQL database

6.1, insert data into the table

The insert statement can be used to insert one or more rows of data into a database table. The general form used is as follows:

insert [into] 表名 [(列名1, 列名2, 列名3, ...)] values (1,2,3, ...);

The content in [] is optional. For example, to insert a record into the students table in the samp_db database, execute the statement:

insert into students values(NULL, "王刚", "男", 20, "13811371377");

And press Enter to confirm if prompted Query Ok, 1 row affected (0.05 sec)represent data inserted successfully. If the insertion fails, please check whether the database to be operated has been selected.

Sometimes we only need to insert part of the data, or insert it out of the order of the columns, we can use this form to insert:

insert into students (name, sex, age) values("孙丽华", "女", 21);

6.2, query the data in the table

6.2.1, query all data

The select statement is often used to obtain data from the database according to certain query rules. Its basic usage is:

select 列名称 from 表名称 [查询条件];

For example: To query the students table for all students' names and ages, input statement select name, age from students;execution results are as follows:

mysql> select name, age from students;
+--------+-----+
| name   | age |
+--------+-----+
| 王刚   |  20 |
| 孙丽华 |  21 |
| 王永恒 |  23 |
| 郑俊杰 |  19 |
| 陈芳   |  22 |
| 张伟朋 |  21 |
+--------+-----+
6 rows in set (0.00 sec)
mysql>

You can also use the wildcard * to query all the contents of the table, the statement:

select * from students;

6.2.2, query data according to specific conditions

The where keyword is used to specify query conditions, and the usage form is:

select 列名称 from 表名称 where 条件;

For example: to query all information whose gender is female as an example, enter the query sentence as follows:

select * from students where sex="女";

The where clause not only supports "where column name = value", the query form whose name is equal to the value, but also supports general comparison operators, such as =, >, <, >=, <, != and Some spread operators are [not] null, in, like, etc. You can also use or and and for the query conditions to perform a combined query, and you will learn more advanced query methods in the future, so I won’t introduce more here.

E.g:

  • Query the information of all persons over 21 years old:
select * from students where age > 21;
  • Query the information of all people with the word "王" in their names:
select * from students where name like "%王%";
  • Query the information of all people with id less than 5 and age greater than 20:
select * from students where id<5 and age>20;

6.3, update the data in the table

The update statement can be used to modify the data in the table, and the basic usage form is:

update 表名称 set 列名称=新值 where 更新条件;

E.g:

  • Change the phone number with id 5 to the default "-":
update students set tel=default where id=5;
  • Increase everyone's age by 1:
update students set age=age+1;
  • Change the name of the mobile phone number 13288097888 to "Zhang Weipeng" and the age to 19:
update students set name="张伟鹏", age=19 where tel="13288097888";

6.4, delete the data in the table

The delete statement is used to delete the data in the table. The basic usage is:

delete from 表名称 where 删除条件;

E.g:

  • Delete the row with id 2:
delete from students where id=2;
  • Delete all data younger than 21 years old:
delete from students where age<20;
  • Delete all data in the table:
delete from students;

7. Modifications after creation

The alter table statement is used to modify the table after creation.

7.1, add column

Basic form:

alter table 表名 add 列名 列数据类型 [after 插入位置];

Example:

  • Append the column address at the end of the table:
alter table students add address char(60);
  • Insert the column birthday after the column named age:
alter table students add birthday date after age;

7.2, modify the column

The basic form is as follows:

alter table 表名 change 列名称 列新名称 新数据类型;

Example:

  • Rename the tel column of the table to telphone:
alter table students change tel telphone char(13) default "-";
  • Change the data type of the name column to char(16):
alter table students change name name char(16) not null;

7.3, delete column

The basic form is as follows:

alter table 表名 drop 列名称;

Example:

  • Delete the birthday column:
alter table students drop birthday;

7.4, rename the table

The basic form is as follows:

alter table 表名 rename 新表名;

Example:

  • Rename the students table to workmates:
alter table students rename workmates;

7.5, delete the entire table

Basic form: drop table 表名;
Example: delete the workmates table:drop table workmates;

7.6, delete the entire database

The basic form is as follows:

drop database 数据库名;

Example:

  • Delete the samp_db database:
drop database samp_db;

8. Appendix

8.1. Modify root user password

According to the installation method in this article, the root user does not have a password by default, and there are many ways to reset the root password. Here is only one of the more commonly used methods, using the mysqladmin method:

Open the command prompt interface, enter the directory mysql\bin under DOS, and execute the command:

mysqladmin -u root -p password 新密码

After execution, you will be prompted to enter the old password to complete the password modification. When the old password is empty, just press the Enter key to confirm.

8.2. Recommended visual management tools

Visual management tools MySQL Workbench, Navicat Premium.


to sum up

This article is the first article of the MySQL database column. It is suitable for beginners with a zero foundation to learn MySQL database. It has everything from installation to uninstallation. At the same time, it summarizes some commonly used MySQL commands. Hope this article can help you get started with MySQL database.

Insert picture description here


I am Bailu, a programmer who works tirelessly. Hope this article can be of benefit to you, welcome everyone's one-click three-connection! If you have any other questions, suggestions or supplements, you can leave a message at the bottom of the article, thank you for your support!
More information WeChat search public accountWDeerCode code circle

Guess you like

Origin blog.csdn.net/qq_22695001/article/details/91356251