An article to lay a good foundation for SQL, familiar with the basic operations and methods of the database, and install the MySQL software package and Python to operate the basic use of MySQL

 1. Overview of SQL

The full name of SQL: Structured Query Language, Structured Query Language, a standard computer language for accessing and processing databases .

The SQL language was proposed by Boyce and Chamberlin in 1974, and was first implemented on the relational database system SystemR developed by IBM.

After years of development, SQL has become the standard language for data manipulation in the database field. It can be said that almost all database systems on the market support operations using the SQL language.

Classification of SQL language :

Since the database management system (database software) has many functions, it not only stores data, but also includes data management, table management, library management, account management, authority management and so on.

Therefore, the SQL language based on the operation database is also divided into four categories based on this function:

  1. Data definition: DDL (Data Definition Language)

    Create and delete libraries, create and delete tables, etc.

  2. Data manipulation: DML (Data Manipulation Language)

    Add data, delete data, modify data, etc.

  3. Data control: DCL (Data Control Language)

    Add new users, delete users, modify passwords, rights management, etc.

  4. Data query: DQL (Data Query Language)

    Query and calculate data based on requirements

Syntactic features of SQL :

Before learning DDL, DQL, etc., let's first understand the grammatical features of SQL.

  1. SQL language, case insensitive

  2. SQL can be written in a single line or multiple lines, and ends with a ;

  3. SQL support comments:

  4. Single-line comment: -- comment content (-- there must be a space after it)

  5. Single-line comment: # Comment content (no space can be added after #, it is recommended to add)

  6. Multi-line comment: /* comment content */

show 
-- This is the first annotation method
# This is the second annotation method
/* Multi-line comment
 * 
 */
databases;

 

 2. SQL DDL

DDL refers to the data definition language, which is used to establish deletion definitions for the database tables in the database.

Create library :

# view the database
SHOW DATABASES
# use the database
USE database name:
# create database
CREATE DATABASE database name [CHARSET UTF8]:
# delete database
DROP DATABASE database name;
# View the currently used database
SELECT DATABASE();

Create and drop tables :

 

 

# See what tables are there
SHOW TABLES; # Note that the database must be selected first
# create table
create table table name (
    column name column type,
    column name column type,
    ……
);
drop table table name;
drop table if exists table name;
drop table where conditional;

column type :

-- Column type:
int -- an integer
float -- floating point number
varchar(length) -- text, the length is a number, and the maximum length is limited
date -- date type
timestamp -- timestamp type

3. SQL DML

DML refers to the data manipulation language, which is used to update the data records in the tables in the database.

keywords:

  1. insert INSERT

  2. delete DELETE

  3. updateUPDATE

Basic grammar :

insert into table (column 1, column 2, column 3, column 4, ..., column N) values ​​(value 1, value 2, value 3, ..., value N) [(value 1, value 2, value 3, ...,valueN),...,(value1,value2,value3,...,valueN)]

Example :

create table student(
    id int,
    name varchart(20),
    age int
);
# Insert only id data
insert into student(id) values(1000),(1002),(1003);
# Insert all id column data
insert into student(id, name, age) values(1001, 'Zhang San', 20),(1002, 'Li Si', 19),(1003, 'Wang Wu', 21);
# Insert all column data, shortcut writing
insert into student values(1001, 'Zhang San', 20),(1002, 'Li Si', 19),(1003, 'Wang Wu', 21);

Data deletion DELETE :

Basic grammar :

DELETE FROM table name WHERE condition judgment
Conditional judgment: column operator value
Operators: = < > <= >= != etc.:
id = 5
id < 3
id >= 6
id != 5

Demo case :

CREATE TABLE student(
    id int,
    name varchar(10),
    age int
);
INSERT INTO student(id) values(1), (2), (3);
/*
 * 等价于下面的代码
 * INSERT INTO student(id) values(1);
 * INSERT INTO student(id) values(2);
 * INSERT INTO student(id) values(3);
*/
insert into student(id, name, age) values(4, '张三', 31),(5, '李四',33);
delete from student where age = 33;

4. SQL DQL

1. Basic query

Basic grammar:SELECT 字段列表|* FROM表

The meaning is: from the (FROM) table, select (SELECT) some columns for display

Code demo :

select id, name from student;
select * from student;
select * from student where age > 20;
select * from student where id = '张三';

2. Group aggregation

Group aggregation application scenarios, such as: counting the number of boys and girls in a class.

This need requires:

  1. group by gender

  2. Count the number of people in each group

This is called: group aggregation.

Basic grammar :

select field | aggregate function from table [where condition] group by column
aggregate function:
sum(column) sum
avg(column) average value
min(column) Find the minimum value
max(column) Find the maximum value
count(column|*) find the quantity

Example :

select gender, avg(age), sum(age), min(age), max(age), count(avg) from student group by gender;

3. Sort pagination

Sort results :

The query results can order bybe sorted by using keywords and specifying a certain column. The syntax is:

select column|aggregation function|* from table
where ……
group by ……
order by …… [ASC | DESC]

Example :

select * from student where age > 20 order by age asc;
select * from student where age > 20 order by age desc;

Results pagination limit :

limitSimilarly, keywords can be used to limit the number of query results or display them in pages. The syntax is:

select column|aggregation function|* from table
where ……
group by ……
order by …… [asc | desc]
limit n[, m]

Example :

select * from student limit 10; # Get 10 pieces of information
select * from student limit 10, 5; # Take 5 from the 11th
select * from student where age > 20 group by age
order by age limit 3;

5.Python operation MySQL basic use

1. Basic use

pymysql

In addition to using graphical tools, we can also use programming languages ​​to execute SQL to operate the database.

In Python, use a third-party library: pymysql to complete operations on the MySQL database.

Install:pip install pymysql

 

 But, at the beginning, I couldn’t download it in my command prompt. At this time, follow the green code behind To update run in the notice and paste it below to operate:

 

 Or use the following methods:

pip install pymysql -i http://pypi.douban.com/simple/ --trusted-host [pypi.douban.com](http://pypi.douban.com/)

 

 Create a database link to MySQL

code show as below:

from pymysql import Connection
# 获取到MySQL数据库的连接对象
conn = Connection(
    host='localhost', # 主机名(或者IP地址)
    port=3306,        # 端口,默认3306
    user='root',      # 账户名
    password='123456' # 密码
)
# 打开MySQL数据库软件信息
print(conn.get_server_info())
# 关闭到数据库的链接
conn.close()

Or enter the following code:

import pymysql
db = pymysql.connect(
    host="localhost",
    port=3306,
    user='root',    #在这里输入用户名
    password='qazwsxedc.2345',     #在这里输入密码
    charset='utf8mb4'
    ) #连接数据库
cursor = db.cursor() #创建游标对象
sql = 'show databases' #sql语句
cursor.execute(sql)  #执行sql语句
one = cursor.fetchone()  #获取一条数据
print('one:',one)
many = cursor.fetchmany(3) #获取指定条数的数据,不写默认为1
print('many:',many)
all = cursor.fetchall() #获取全部数据
print('all:',all)
cursor.close()
db.close()  #关闭数据库的连接

 

 The interface shown above shows that pymysql has successfully connected pycharm and mysql.

Execute query-like SQL statements :

from pymysql import Connection
# 获取到MySQL数据库的连接对象
conn = Connection(
    host='localhost',
    port=3306,
    user='root',
    password='2345'
)
# 获取游标对象
cursor = conn.cursor()
conn.select_db("world")
# 使用游标对象,执行sql语句
cursor.execute("SELECT * FROM student")
# 获取查询结果
results = cursor.fetchall()
for r in results:
    print(r)
# 关闭到数据库的链接
conn.close()

2. Data insertion

commitSubmit

When pymysql executes data insertion or other SQL statements that generate data changes, it needs to submit the changes by default, that is, it needs to "confirm" this change behavior through code.

This behavior can be confirmed by linking object .commit().

from pymysql import Connection
# 获取到MySQL数据库的连接对象
conn = Connection(
    host='localhost',
    port=3306,
    user='root',
    password='2345'
)
# 获取游标对象
cursor = conn.cursor()
conn.select_db("world")
# 使用游标对象,执行sql语句
cursor.execute("insert into student values(10001, '唐七', 19)")
# 关闭到数据库的链接
conn.close()

6. Comprehensive case

Use SQL statements and pymysql library to complete the development of comprehensive cases

 

 DDL definition :

For this demand development, we need to create a new database to use, database name: py_sql

Based on the data structure, the table creation statement can be obtained:

CREATE TABLE order(
    order_date DATE,
    order_id, VARCHAR(255),
    money INT,
    province VARCHAR(10)
);

Implementation steps :

Read data -> Encapsulate data object -> Build database link -> Write to database

import ..
text_file_reader = TextFileReader("D:/2011年1月销售数据.txt")
json_file_reader = JsonFileReader("0:/2011年2月销售数据JS0N.txt")
jan_data:list[Record] = text_file_reader.read_data()
feb_data:list[Record] = json_file_reader.read_data()
# 将2个月份的数据合并list来存储
all_data:list[Record] = jan_data + feb_data
    
# 构建MySQL链接对象
cursor = conn.cursor()
conn.select_db("py_sql")
# 组织SQL语句
for record in all_data:
    sql = f"insert into orders(order_data, order_id, money, province)" 
    	f"values('{record.date}','{record.order_id)'{record.noney},'{record.province}')"
	print(sql)
    cursor.excute(sql)
conn.close()

Guess you like

Origin blog.csdn.net/Williamtym/article/details/130793323