Mysql Xiaobai study notes

Getting Started with Databases

DB
DBMS

ER model

1) Three elements of ER diagram

(1) Entity: The entity is represented by a rectangle, and the entity name is marked inside the rectangle.
(2) Attribute: The attribute is represented by an oval, and the attribute name is marked inside the oval, and connected with the entity by a connection line.
(3) Connections between entities: Use rhombuses to represent the connections between entities, and indicate the name of the connection inside the diamond, connect the diamonds to related entities with connecting lines, and indicate the connection type on the connecting lines.

Relationship between two entities: There are relationships other than many-to-one.

Relationships between more than two entities: all except one-to-many.

image.png

A insert image description here
student can have one student ID card, and must only have one student ID card.
insert image description here

A student must and can only be in one class. The maximum number of students in a class is 40, and the minimum number is 30.

Author: Little Lucky Q
Link: https://www.jianshu.com/p/19610fafcc2b
Source: Jianshu
The copyright belongs to the author. For commercial reprint, please contact the author for authorization, for non-commercial reprint, please indicate the source.

relational schema

relation_name(property1,property2...)

Mysql

installation method

The port number

Mysql related commands

? (?) Synonym for `help’. 。。。。。。。
clear (\c) Clear the current input statement.
connect (\r) Reconnect to the server. Optional arguments are db and host.
delimiter (\d) Set statement delimiter.
ego (\G) Send command to mysql server, display result vertically.
exit (\q) Exit mysql. Same as quit.
go (\g) Send command to mysql server.
help (\h) Display this help.
notee (\t) Don’t write into outfile.
print (\p) Print current command.
prompt (\R) Change your mysql prompt.
quit (\q) Quit mysql.
rehash (#) Rebuild completion hash.
source (.) Execute an SQL script file. Takes a file name as an argument. execute a script
status (\s) Get status information from the server.
tee (\T) Set outfile [to_outfile]. Append everything into given outfile.
use (\u) Use another database. Takes database name as argument.
charset (\C) Switch to another charset. Might be needed for processing binlog with multi-byte charsets.
warnings (\W) Show warnings after every statement.
nowarning (\w) Don’t show warnings after every statement.
resetconnection (\x) Clean session context.

Basic operation of database

  1. SHOW DATABASE; Check the database, pay attention to the S behind it, forgot several times
  2. CREATE DATABASE database name
  3. How to view the database path established in 2——show variables like 'datadir';
    insert image description here
  4. View the details of the established database - SHOW CREATE DATABASE
  5. Modify the database encoding method - there are many pits here

Modify database encoding

  • latin1, this 1 is exactly the same as l in the command line, the following is a series of error reports, to be resolved
mysql> ALTER DATABASE hzh DEFAULT CHARACTER
    -> SET latinl COLLATE gbk;
ERROR 1115 (42000): Unknown character set: 'latinl'
mysql>  ALTER DATABASE hzh DEFAULT CHARACTER
    -> SET latin1 COLLATE gbk;
ERROR 1273 (HY000): Unknown collation: 'gbk'
mysql> ALTER DATABASE hzh DEFAULT CHARACTER
    -> SET latin1 COLLATE utf8;
ERROR 1273 (HY000): Unknown collation: 'utf8'
mysql> ALTER DATABASE hzh DEFAULT CHARACTER
    -> SET latin1 COLLATE utf-8;
ERROR 1273 (HY000): Unknown collation: 'utf'
mysql> ALTER DATABASE hzh DEFAULT CHARACTER
    -> SET latin1 COLLATE gbk_bin;
ERROR 1253 (42000): COLLATION 'gbk_bin' is not valid for CHARACTER SET 'latin1'
mysql> ALTER DATABASE hzh DEFAULT CHARACTER
    ->  SET latin1 COLLATE utf8_general_ci;
ERROR 1253 (42000): COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'

Basic operation of data table

  1. Display mode: int(M) In the integer data type, M represents the maximum display width.
    In int(M), the value of M has nothing to do with how much storage space int(M) occupies.

  2. Create a table, and do not add , after the last element definition in the table is completed ! ! ! ! !

mysql> CREATE TABLE HOBBY(
    -> ho_id INT(10),
    -> ho_name VARCHAR(50),
    -> ho_fre INT(6),
    -> );
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 5
  1. Looking at the datasheet, the method is different from the tutorial I chose
mysql> SHOW CREATE TABLE hobby;
+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table                                                                                                                                                       |
+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| hobby | CREATE TABLE `hobby` (
  `ho_id` int(10) DEFAULT NULL,
  `ho_name` varchar(50) DEFAULT NULL,
  `ho_fre` int(6) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+-------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
  1. I don’t know why SHOW CREATE TABLE hobby\G;this is an error
    , use DESC to view
mysql> DESC hobby;
+---------+-------------+------+-----+---------+-------+
| Field   | Type        | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| ho_id   | int(10)     | YES  |     | NULL    |       |
| ho_name | varchar(50) | YES  |     | NULL    |       |
| ho_fre  | int(6)      | YES  |     | NULL    |       |
+---------+-------------+------+-----+---------+-------+
  1. int(M) In the integer data type, M represents the maximum display width. In int(M), the value of M has nothing to do with how much storage space int(M) occupies.

Basic operations on data in tables

  1. decimal(10,2) - 2 digits for the fractional part and 8 digits for the integer part
  2. SHOW TABLES;View the table that has been created;
  3. Insert data in bulk:
mysql> INSERT INTO emp(id,name)
    -> VALUES(1,'sunkaien'),(3,'future');
  1. View table (distinguish DESC instruction)
 mysql> SELECT *FROM 表名;
+------+----------+--------+----------+--------+------------+--------+
| id   | name     | gender | birthday | salary | entry_date | resume |
+------+----------+--------+----------+--------+------------+--------+
|    1 | sunkaien | NULL   | NULL     |   NULL | NULL       | NULL   |
|    3 | future   | NULL   | NULL     |   NULL | NULL       | NULL   |
+------+----------+--------+----------+--------+------------+--------+
  1. Update all data UPDATE emp(表名) SET gender='male';
    Update some data UPDATE emp SET salary=5000 WHERE name='sunkaien';Note that this where is followed by a filter condition.
  2. Delete data
    Delete part of the data DELETE FROM table name [WHERE conditional expression];
  3. Query specified fields
  SELECT 字段名  FROM 表名;
  1. Relational operators · query with conditions
    =——equal to
    <>——not equal to (recommended to use this)
    !=——not equal to
    <——less than
    <=——less than or equal
    In addition, there are IN and NOT IN statements
    Understand the similarities and differences of the following conditional query statements:
mysql> SELECT age FROM stu
    -> WHERE age>=24;
+-----+
| age |
+-----+
|  24 |
|  26 |
|  24 |
+-----+

mysql> SELECT *FROM stu
    -> WHERE age>=24;
+--------+----------+-----+--------+
| sid    | sname    | age | gender |
+--------+----------+-----+--------+
| S_1003 | hzh      |  24 | male   |
| S_1004 | zhangli  |  26 | female |
| S_1005 | zhaoyuan |  24 | male   |
+--------+----------+-----+--------+

Query for NULL information:

mysql> SELECT *FROM emp
    -> WHERE salary IS NULL;
  1. fuzzy query
 mysql> SELECT *FROM stu
    -> WHERE sname LIKE 'z%';#LIKE后面跟匹配字符串

% (percent sign) means any 0~n characters, _ (underscore) means any character

  1. Remove duplicate keywords from query results
    using DISTINCT
mysql> SELECT DISTINCT gender FROM stu;
+--------+
| gender |
+--------+
| female |
| male   |
+--------+

Advanced Search

  1. Sort query
 mysql> SELECT * FROM stu
    -> ORDER BY age ASC;#ASC代表升序排列,DESC代表降序
    -> SELECT * FROM stu
    -> ORDER BY age ASC,sid DESC;#并列多个拆寻条件时,优先满足第一个,再第一个无法排序时,再看第二个。
  1. Sort and sum operation
    SELECT function name (field name) FROM table name;
    function: SUM sum AVG average value MAX MIN
  2. group operation
 mysql> SELECT gender,AVG(age) FROM stu  #排序依据
    -> GROUP BY gender; #分组依据
  1. LIMIT paging
    limit the number of query results

PyMysql

basic reading and writing

import pymysql
db=pymysql.connecte("localhost","root","1234","future")

cursor=db.cursor()

cursor.execute("SELECT VERSION()")

data=cursor.fetchone()

print("Database version:%s"% data)

db.close()

1

AttributeError: 'module' object has no attribute 'connect'  

connect error
2

TypeError: __init__() takes 1 positional argument but 5 were given

**db=pymysql.connect(host="localhost", user="root", password="1234", database="hzh")**Python version reasons, you need to add a name before the parameter

operation result:

Database version:5.7.24-log

Getting started with Navicat

  1. View the database and add and delete entries.
    Maybe we connect to the local database at the beginning and find that there is no table. At this time, right-click our local database local databaseand select Edit connection, as shown in the figure below, in the Database tab, we will create Check the list.

insert image description here
Double-click the local server to connect, and then the data table on the machine is also displayed
insert image description here

  1. Modify the data table
    Double-click the table to be modified, enter the edit, look at the red circle in the lower right corner, you can add or delete data entries, is it very convenient?
    insert image description here
    I right-clicked to create a new database, and after refreshing the host, I found that it was not there, and then thought of editing the connection? ? ? The database is not checked,
    insert image description here
    and then run the file in the built database.
    Or just cancel the use of custom database list directly.

Guess you like

Origin blog.csdn.net/weixin_54594861/article/details/115366169