[Notes] python MySQL MySQL basic use

[Notes] python MySQL MySQL basic use

table of Contents

1. Introduction to Database

2. MySQL Installation

2.1. Server-side installation

2.2. Client Installation

3. Data Integrity

3.1. Data Types

3.2. Constraints

The command-line script

5.1. Database Operations

5.2 The data in Table operation

5.3. Data CRUD (important)


 

mysql official website Documentation: https://dev.mysql.com/doc/refman/5.7/en/

1. Introduction to Database

Database is a special file, which stores the data needed.

The current major use of two types of database: relational database , non-relational database , this section focuses on relational databases.

NOTE: To view a database ranking: https://db-engines.com/en/ranking

 

Relational Database:

Relational database core elements:

  • Data rows (records)
  • Data column (field)
  • Data Sheet (set data row)
  • Database (a collection of data tables)

 

RDBMS:

That RDBMS  Relational Database Management System (relational database management system), is a program;

In the relational model database is established on the basis by means of a set of mathematical concepts and methods to process algebra data in the database.

The main relational database products:

  • oracle: used in previous large-scale projects in banking, telecommunications and other projects
  • mysql: web era's most widely used relational database
  • ms sql server: use in Microsoft Project
  • sqlite: lightweight database, mainly used in mobile platforms

 

The relationship between RDBMS and database:

RDBMS to manage files through a database. But RDBMS generally very complex, it is generally made of the RDBMS CS architecture, ordinary users through client with SQL to communicate statements and database.

 

SQL:

SQL (Structured Query Language) that is structured query language.

SQL is Structured Query Language, is a language used to operate the RDBMS database, relational database currently support the use of SQL language to operate, which means you can operate the database through SQL oracle, sql server, mysql, sqlite and other relational .

  • SQL statements are divided into:
    • DQL: data query language for data query, such as select
    • DML: Data Manipulation Language, the data add, modify, delete, such as insert, udpate, delete
    • TPL: transaction processing language, transaction processing, including the begin transaction, commit, rollback
    • DCL: Data Control Language, authorization and permissions recovery, such as grant, revoke
    • DDL: data definition language, a database, a management table or the like, such as create, drop
    • CCL: pointer control language, by controlling the operation of the pointer table is completed, as declare cursor
  • For web programmer is concerned, the focus is crud data (CRUD), must prepare skilled DQL, DML, DDL complete the operation to write the database, tables , other languages such as TPL, DCL, CCL can learn
  • SQL is a special language, specifically designed to operate relationship database
  • not case sensitive

 

MySQL Features:

  • Written in C and C ++, and uses a variety of compilers tested to ensure source code portability

  • Support multiple operating systems, such as Linux, Windows, AIX, FreeBSD, HP-UX, MacOS, NovellNetware, OpenBSD, OS / 2 Wrap, Solaris, etc.

  • It provides an API for a variety of programming languages ​​such as C, C ++, Python, Java, Perl, PHP, Eiffel, Ruby, etc.

  • Multi-threading, make full use of CPU resources

  • SQL query optimization algorithms, effectively speed up the search
  • It provides multi-language support, common coding such as GB2312, BIG5, UTF8
  • Provide TCP / IP, ODBC and JDBC database connectivity and other ways
  • To provide for management, check, optimize database operations management tools
  • Large databases. You can handle tens of millions of records have a large database
  • Support for multiple storage engines
  • MySQL software uses a dual licensing policy, which is divided into community and commercial versions, because of its small size, high speed, low cost of ownership, especially open source this feature, the development of small and medium websites have chosen MySQL as the database website
  • MySQL data using standard SQL language form
  • Mysql can be customized using the GPL agreement, you can modify the source code to develop their own systems Mysql
  • Online DDL change function
  • Copy the global transaction identifier
  • No copy machine from collapse
  • Copy multi-threaded slaves
  • Open source, free, using a wide range of cross-platform support and good, provided API calls in multiple languages, learning is the preferred database development

 

 

 

2. MySQL Installation

MySQL 5.7 Reference Manual: https://dev.mysql.com/doc/refman/5.7/en/

2.1. Server-side installation

In Ubuntu, enter the following commands in the terminal, after the transport, and then follow the prompts:

sudo apt-get install mysql-server
  • Server receives a request for a client, sql statement execution, database management
  • General server management as a service, named mysql
  • Start service: sudo Service Start MySQL
  • Check whether there is a process in mysql service: PS -aux | grep mysql  (PS -aux display process information, I pipeline, grep mysql  search mysql; top dynamic display of process information)
  • Stop Service: sudo STOP MySQL Service
  • Restart the service: sudo restart MySQL Service

 

Configuration:

  • Profile directory file: /etc/mysql/mysql.cnf, in addition to outside comments containing the following statement:

!includedir /etc/mysql/conf.d/

!includedir /etc/mysql/mysql.conf.d/

 

  • Enter conf.d directory, open mysql.cnf, discovery and no configuration
  • Enter mysql.conf.d directory, open mysql.cnf, you can see the configuration items, configuration items mainly as follows:

 

  • bind-address binding means that the server ip, the default is 127.0.0.1
  • port the port, the default is 3306
  • datadir represents the database directory, defaults to / var / lib / mysql
  • general_log_file represent ordinary log, the default is /var/log/mysql/mysql.log
  • log_error an error log, the default is /var/log/mysql/error.log

 

2.2. Client Installation

The client is a developer and dba use, by way of socket communication with the server, commonly used navicat, command line mysql. Often developers use the command-line SQL statements.

 

Command Line Client:

  • Run command in the terminal installation : the sudo APT-GET-Client the install MySQL
  • Command detailed connections can help documentation: MySQL --help
  • The most basic connection command as follows: MySQL-uroot--pmysql (ie  mysql -u username -p password  )
  • After a successful connection will prompt: Welcome to the MySQL monitor ..... and other information
  • Press ctrl + d or enter the following command to exit: quit or exit 

 

 

Graphical interface client navicat :( understand)

  • To Navicat's official website to download (fee, 14-day trial)
  • The compressed files are copied to ubuntu, the decompression: tar file name zxvf
  • Unzipped into the directory, run the following command: ./start_navicat
  • Click Click twice to cancel the trial, you can open the software interface
  • (Update: new version of ubuntu to copy, you can directly open)

 

1. Chinese garbled Solution: Open the file start_navicat

The export LANG = "en_US.UTF-8" to export LANG = "zh_CN.UTF-8"

 

2. After the trial period expires: Delete .navicat64 directory under the user directory, rerun ./start_navicat installation. ( Update: This method fails. )

cd ~

rm -r .navicat64

 

 

 

3. Data Integrity

A database is a complete business unit, may contain multiple tables , the data is stored in the table; the table in order to more accurately stored data, to ensure data is correct and effective when you can create a table, add some mandatory table verification, including data field types , constraints .

Better content of the reference document mysql official website: https://dev.mysql.com/doc/refman/5.7/en/

3.1. Data Types

Note: a more complete description refer to the relevant documentation mysql: https://dev.mysql.com/doc/refman/5.7/en/data-types.html

 

  • Common data types are as follows :
    • Integer: int, bit
    • Decimal: decimal
    • Strings: varchar, char
    • Date Time: date, time, datetime
    • Enumerated types (enum)
  • Type particularly described as follows :
    • decimal represent floating-point , decimal, such as (5,2) indicates a coexistence 5 digit decimal accounting 2;
    • char string representing a fixed length, such as char (. 3), will be supplemented if the filling 'ab' is a space'ab ';
    • It represents a variable-length string varchar , such as varchar (. 3), to store a 'ab' filling 'ab';
    • String text denotes a storage large text , when the character is greater than the recommended 4000;
    • For pictures, audio, video and other large files are not stored in the database , but uploaded to a server, and then in the table storage path to save the file  .

Common data types :

Numeric Data Types

Types of Byte size Signed range (Signed) Unsigned range (Unsigned)
TINYINT 1 -128 ~ 127 0 ~ 255
SMALLINT 2 -32768 ~ 32767 0 ~ 65535
MEDIUMINT 3 -8388608 ~ 8388607 0 ~ 16777215
INT/INTEGER 4 -2147483648 ~2147483647 0 ~ 4294967295
BIGINT 8 -9223372036854775808 ~ 9223372036854775807 0 ~ 18446744073709551615

 

String Data Types

Types of Byte size Examples
CHAR 0-255 Type: char (3) Enter 'ab', to actually store 'ab', enter 'abcd' is actually stored as 'abc'
VARCHAR 0-255 Type: varchar (3) output 'ab', to actually store 'ab', enter 'abcd', actually stored as 'abc'
TEXT 0-65535 Large Text

 

Date and Time Data Types

Types of Byte size Examples
DATE 4 '2020-01-01'
TIME 3 '12:29:59'
DATETIME 8 '2020-01-01 12:29:59'
YEAR 1 '2017'
TIMESTAMP 4 '1970-01-01 00:00:01' UTC ~ '2038-01-01 00:00:01' UTC

NOTE: Use the data type principle is enough on the line, to make use of a small range .

 

3.2. Constraints

  • Primary Key primary key: a sequence of physical storage
  • Non-null not null: This column is not allowed to fill empty value
  • The only unique: The value of this field is not allowed to repeat
  • Default default: When not fill this value will use the default values ​​to fill prevail if the fill
  • Foreign key foreign key: to constrain the relationship field, when the field is filled relationship value, will go to the table associated query this value exists, if there is then complete success, if it does not exist to fill fails with an exception. Popular speaking, the other table's primary key stored in a field called foreign keys .
  • Description: Although the foreign key constraint can guarantee the validity of the data, but during the crud data (add, modify, delete, query) when, will reduce the performance of the database, it is not recommended , the validity of the data can also be at the logical level control .

 

The command-line script

  • Connect to the database : MySQL -uroot--p , password carriage return ( mysql -u username -p password  or  mysql -u username -p [ENTER]  and then enter a password)
  • View version: select version ();
  • Shows the current time: select now ();
  • Press ctrl + d or enter the following command to exit: quit or exit 

5.1. Database Operations

Common database operations:

View all databases

show databases;

Use Database

use 数据库名;

View current database used

select database();

Create a database ( Note : If the database name with dashes, need to add back quotes `` in the upper left corner of the keyboard

create database 数据库名 charset=utf8;
例:
create database python charset=utf8;

create database `python-test` charset=utf8;

Delete Database

drop database 数据库名;
例:
drop database python;

 

Related notes :

-- 数据库的操作  (注释以 "--" 开头)

    -- 链接数据库
    mysql -uroot -p
    mysql -uroot -pmysql

    -- 退出数据库
    exit/quit/ctrl+d
    

    -- sql语句最后需要有分号;结尾
    -- 显示数据库版本
    select version();

    -- 显示时间
    select now();

    -- 查看所有数据库
    show databases;
    

    -- 创建数据库
    -- create database 数据库名 charset=utf8;
    -- 注:若数据库名带小横线,需加反引号`
    create database python_test;
    create database python_testnew charset=utf8;
    create database `python-test`;


    -- 查看创建数据库的语句
    -- show crate database ....
    show create database python_test;
    

    -- 查看当前使用的数据库
    select database();

    -- 使用数据库
    -- use 数据库的名字
    use python_test;

    -- 删除数据库
    -- drop database 数据库名;  
	-- 注:若数据库名带小横线,需加反引号`
    drop database python_test;

 

 

5.2 The data in Table operation

Use use database name;   the database is used, it can operate on the data table.

Related operations notes:


-- 数据表的操作------------------------------------------------------------------

    -- 查看当前数据库中所有表
    show tables;
    
	
    -- 创建表---------------------------------
    -- auto_increment表示自动增长
    -- not null 表示不能为空
    -- primary key 表示主键
    -- default 默认值
	
    -- create table 数据表名字 (字段 类型 约束[, 字段 类型 约束]);
    create table xxxxx(id int, name varchar(30));  --有个int类型的id字段,varchar类型的name字段
	
	-- id加上约束:主键、非空、自动增长;如下
    create table yyyyy(id int primary key not null auto_increment, name varchar(30)); 
	
	-- 写成多行,提高可读性
    create table zzzzz(
        id int primary key not null auto_increment,
        name varchar(30)  --最后一个不需要逗号
    );

	
    -- 查看表结构
    -- desc 数据表的名字;
    desc xxxxx;
	
	
	
	

-- !练习:创建学生表和班级表----------------------
	
    -- 创建students表(id、name、age、high、gender、cls_id)
    create table students(
        id int unsigned not null auto_increment primary key,  -- unsigned 无符号类型
        name varchar(30),
        age tinyint unsigned default 0,
        high decimal(5,2), 
        gender enum("男", "女", "中性", "保密") default "保密",
        cls_id int unsigned  
    );
	
	-- 插入一个数据
    insert into students values(0, "老王", 18, 188.88, "男", 0); 
	
	-- 查看数据
    select * from students;

	
    -- 创建classes表(id、name)
    create table classes(
        id int unsigned not null auto_increment primary key,
        name varchar(30)
    );

    insert into classes values(0, "python班01");
    select * from classes;

	
	
	
-- 修改和删除表的 字段--------------------------------
    

    -- 修改表-添加字段
    -- alter table 表名 add 列名 类型;
    alter table students add birthday datetime;
    

    -- 修改表-修改字段:不改字段名版
    -- alter table 表名 modify 列名 类型及约束;
    alter table students modify birthday date;


    -- 修改表-修改字段:改字段名版
    -- alter table 表名 change 原名 新名 类型及约束;
    alter table students change birthday birth date default "2000-01-01";


    -- 修改表-删除字段
    -- alter table 表名 drop 列名;
    alter table students drop high;


    -- 删除表
    -- drop table 数据表名;
	drop table xxxxx;
	
	-- 删库跑路
    -- drop database 数据库;
	
	
	-- !查看表的创建语句
    -- show create table 表名;
    show create table students;
    

Key :

Create a MySQL data tables common SQL syntax:

CREATE TABLE table_name (column_name column_type);
create table 数据表名字 (字段 类型 约束[, 字段 类型 约束]);

 

 

5.3. Additions and deletions to change search data (important)

CURD : create ( the Create ), update ( Update ), read ( Retrieve ) and delete ( the Delete ).

 

Create notes :

Insert syntax :

INSERT INTO table_name ( field1, field2,...fieldN )
                       VALUES
                       ( value1, value2,...valueN );
 -- 增加--------------------------------------
        -- 全列插入----------------------
        -- insert [into] 表名 values(...)
        -- 主键字段 可以用 0  null   default 来占位
        -- 向classes表中插入 一个班级
        insert into classes values(0, "python班02");

		
        --下方语句基于以下表结构:
        +--------+-------------------------------------+------+-----+------------+----------------+
        | Field  | Type                                | Null | Key | Default    | Extra          |
        +--------+-------------------------------------+------+-----+------------+----------------+
        | id     | int(10) unsigned                    | NO   | PRI | NULL       | auto_increment |
        | name   | varchar(30)                         | YES  |     | NULL       |                |
        | age    | tinyint(3) unsigned                 | YES  |     | 0          |                |
        | gender | enum('男','女','中性','保密')       | YES  |     | 保密       |                |
        | cls_id | int(10) unsigned                    | YES  |     | NULL       |                |
        | birth  | date                                | YES  |     | 2000-01-01 |                |
        +--------+-------------------------------------+------+-----+------------+----------------+

        -- 向students表插入 一个学生信息
        insert into students values(0, "小李飞刀", 20, "女", 1, "1990-01-01");
        insert into students values(null, "小李飞刀", 20, "女", 1, "1990-01-01");
        insert into students values(default, "小李飞刀", 20, "女", 1, "1990-01-01");

        -- 失败
        -- insert into students values(default, "小李飞刀", 20, "第4性别", 1, "1990-02-01");

        -- 【枚举中】:下标从1 开始 1---“男” 2--->"女"....
        insert into students values(default, "小李飞刀", 20, 1, 1, "1990-02-01");

		
        -- 部分插入------------------------
        -- insert into 表名(列1,...) values(值1,...)
        insert into students (name, gender) values ("小乔", 2);


        -- !多行插入-----------------------------
        insert into students (name, gender) values ("大乔", 2),("貂蝉", 2);
        insert into students values(default, "西施", 20, "女", 1, "1990-01-01"), (default, "王昭君", 20, "女", 1, "1990-01-01");


 

Update notes :

-- 修改-------------------------------------------------
	
    -- update 表名 set 列1=值1,列2=值2... where 条件;
        update students set gender=1; -- 一列全部都改了
        update students set gender=1 where name="小李飞刀"; -- 只要name是小李飞刀的 全部的修改
        update students set gender=1 where id=3; -- !只要id为3的 进行修改
        update students set age=22, gender=1 where id=3; -- 只要id为3的 进行修改

 

Basic Retrieve notes:

-- 查询基本使用------------------------------------------
	
        -- *查询所有列
        -- select * from 表名;
        select * from students;

        ---条件查询
        select * from students where name="小李飞刀"; -- 查询 name为小李飞刀的所有信息
        select * from students where id>3; -- 查询 name 为小李飞刀的所有信息


        -- 查询指定列
        -- select 列1,列2,... from 表名;
        select name,gender from students;


        -- 可以使用 [as] 为列或表指定【别名】
        -- select 字段[as 别名] , 字段[as 别名] from 数据表 where ....;
        select name as 姓名,gender as 性别 from students;


        -- 字段的顺序
        select id as 序号, gender as 性别, name as 姓名 from students;
    

 

 

Delete notes:

-- 删除----------------------------------------------------
	
        -- 物理删除-------------------
        -- delete from 表名 where 条件
        delete from students; -- 整个数据表中的所有数据全部删除
        delete from students where name="小李飞刀";

        -- 逻辑删除-------------------
        -- 用一个字段来表示 这条信息是否已经不能再使用了
        -- 给students表添加一个 is_delete字段 bit 类型
        alter table students add is_delete bit default 0;
		-- 用更改字段值代表删除
        update students set is_delete=1 where id=6;

 

Attachment:

mysql official website Documentation: https://dev.mysql.com/doc/refman/5.7/en/

w3school Tutorial: https://www.w3school.com.cn/sql/index.asp

 

------end-------

Published 50 original articles · won praise 10 · views 6612

Guess you like

Origin blog.csdn.net/qq_23996069/article/details/104304077