Python-MySQL database foundation (3) MySQL and python interaction

MySQL interacts with python

insert image description here
Use python code to connect to the database, execute SQL statements, and query the data in the database.
When there is a large amount of data in a table, and we only need to query the data in a certain field, direct query will lead to a decrease in efficiency, so we need to create sub-tables.

Python operation MySQL steps

Install pymysql

pip install pymysql

connection object, establish a connection with the database, create an object: call the connect() method.
cursor, cursor, read data line by line.
insert image description here
The code implementation process is as follows

# 第一种导入
# from pymysql import *
# connect()
# 第二种导入
import pymysql
# 1.连接数据库,user和password 都是直接设置的
conn = pymysql.connect(host='127.0.0.1',port=3306,user='root',password='hww-sql',db='shopping',charset='utf8')
# 2.获取游标对象
cs = conn.cursor()

# 3. 通过游标对象执行sql语句,受影响的行数
r =cs.execute('select * from goods;')
print(r)  # 得到的是数据的条数21

# 4. 获取数据,通过游标获取数据,执行完一行,游标会在第二行
print(cs.fetchone())  # 获取的是第一条数据
print(cs.fetchone())  # 获取的是第二条数据
# 4.1 fechmany(),默认不传参数,返回一条数据
print(cs.fetchmany())
print(cs.fetchmany(2))  # 括号内的数字是获取数据的条数
# 4.2 获取全部的数据
# print(cs.fetchall())  # 获取全部的数据
# 获取全部数据后,再去获取数据就得不到数据,返回None
# print(cs.fetchone())  # None,获取所有数据后,游标在末尾不会重新获取

# 5. 关闭
# 5.1 关闭游标
cs.close()
# 5.2 关闭连接
conn.close()

# 关闭后还可以获取数据,有缓存的
print('*'*50)
print(cs.fetchone())

exception capture

When there is an error in the port number and other information, in order to ensure the normal operation of the program, exception capture is required

import pymysql
try:
    conn = pymysql.connect(host='127.0.0.1',port=3307,user='root',passwd='hww-sql',db='shopping',charset='utf8')
except Exception as e:
    print(e) # e是对象,并不是元组,代表的是Exception
    print(e.args[0])  # 取出第一个值 2003

Package DB

Use classes for encapsulation, divide them into modules separately, and realize a certain function alone.

from pymysql import *

'''
1.连接数据库,在实例化的时候连接数据库
2.实现程序执行完毕后,自动关闭
'''
class MyDb(object):
    # 2.初始化,自动连接数据库
    def __init__(self):
        self.my_conn()
    # 1.定义连接数据库的方法
    def my_conn(self):
        # 实例化方法
        try:
            self.conn = connect(host='127.0.0.1',port=3306,user='root',passwd='hww-sql',db='shopping',charset='utf8')
        except Exception as e:
            print(e)

    # 3. 获取单条数据
    def get_one(self):
        # 3.1 获取游标
        cs = self.conn.cursor()
        # 3.2 执行sql语句
        sql = 'select * from goods'
        # 执行sql语句
        cs.execute(sql)
        # 3.3 获取执行的结果
        res = cs.fetchone()
        # 3.4 只关闭游标
        cs.close()
        return res

    # 4. 获取全部数据
    def get_all(self):
        # 4.1 获取游标
        cs = self.conn.cursor()
        # 4.2 执行sql语句
        sql = 'select * from goods'
        # 执行sql语句
        cs.execute(sql)
        # 4.3 获取执行的结果
        res = cs.fetchall()
        # res = cs.fetchmany(5) # 传入参数值
        # 4.4 只关闭游标
        cs.close()
        return res
    # 关闭连接,需把关闭连接单独定义,否则第二次调用的时候连接就关闭了
    # def close_conn(self):
    #     self.conn.close()
    # 程序执行完毕之后,自动执行关闭的方法
    def __del__(self):
        self.conn.close()
def main():
    # 实例化对象
    db =MyDb()
    # data =db.get_one()  # 每次执行都会创建一个游标
    # print(data)
    # data = db.get_one()  # 访问的始终的第一个数据,因为每次执行都重新创建一个游标
    # print(data)
    all_data = db.get_all()
    # print(all_data)
    # 遍历取出所有数据
    for data in all_data:
        print(data)
if __name__ == '__main__':
    main()

First import the library and encapsulate it with a class. The framework of the code is to define the class, function main(), and the entry of the program. Define the method of connecting to the database, use the init method to automatically connect to the database when it is instantiated, and then obtain data, obtain a single piece of data, first obtain the cursor, then execute the sql statement, obtain the execution result, and finally close the cursor and connection, Return the obtained res to the calling place of the function in the main function. If the function is called twice, an error will be reported, because after the first call, the connection to the database has been closed. In order to obtain data repeatedly, the closed connection needs to be stored separately. The closed cursor does not need to be stored separately, because the cursor is redefined each time the method is called, so each time the value is fetched from the first piece of data. Define a function for obtaining multiple pieces of data, which is similar to the function for obtaining a single piece of data. Call the function in the main function to obtain all the data. The data obtained is a tuple, which can be retrieved one by one by traversal. Optimize the code, and use the del method to automatically close the connection when the code execution ends.

insert data

Import the library, create functions to operate the database, connect to the database, obtain cursors, insert data, execute sql statements, close cursors and connections. The program is running normally but the data cannot be added. At this time, it is an engine problem. MyIsAM can modify the data without submitting the transaction; Innodb needs to submit the transaction (higher security) to modify the data of the table, and you need to use commit before closing the cursor. Submit the transaction, and the content of the data table can be added at this time. If there are multiple sql statements, one commit can submit multiple transactions. An error occurred in the statement of adding data, and the data cannot be added normally, but it will occupy the id in the data table, because the server will receive it.
If multiple sql statements are executed, as long as there is an error, it will not be added. It is like transferring money with a bank card. If the information is wrong, it will automatically return to the original account. Rollback can be used to implement conn.rollback(). Use try, except to catch the problem.

import pymysql
def coperation_db():
    try:
        # 连接数据库
        conn = pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='hww-sql',db='mytest-01',charset='utf8')
        # 获取游标
        cs = conn.cursor()
        # 插入数据
        sql = "insert into mytable1 (name) value ('xiaoming11');"
        # 执行sql语句
        cs.execute(sql)
        # 插入数据
        sql = "insert into mytable1 (name) value ('xiaoming22');"
        # 执行sql语句
        cs.execute(sql)
        # 提交事务,一次性可以提交多个
        conn.commit()
        # 关闭游标
        cs.close()
        # 关闭连接
        conn.close()
    except  Exception as e:
        conn.rollback()
        
if __name__ == '__main__':
    coperation_db()

insert image description here

Use object-oriented to complete the query of goods

'''
输入1:查询所有商品
输入2:所有商品种类
输入3:查询所有品牌
输入4:退出
输入5:插入数据
'''
import pymysql
class Shopping(object):
    def __init__(self):
        self.conn = pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='hww-sql',db='shopping',charset='utf8')
        self.cs =self.conn.cursor()
    # 用户输入的模板
    def run(self):
        while True:
            num = self.print_meun()
            if num == '1':
                self.show_all_goods()
            elif num == '2':
                self.show_all_cates()
            elif num == '3':
                self.show_all_brands()
            elif num == '4':
                break
            elif num == '5':
                self.add_cate()
            else:
                print('你输入的内容错误')
    # 写入的内容不需要参数,不需要self
    # 静态方法的装饰器
    @staticmethod
    def print_meun():
        print('-----shop-----')
        print('输入1:查询所有商品')
        print('输入2:所有商品种类')
        print('输入3:查询所有品牌')
        print('输入4:退出')
        print('输入5:插入数据')
        num = input('请输入选项:')
        return num
    # 查询所有的商品,避免代码重复写,把执行sql语句,获取所有的结果,遍历循环得到的数据单独列出来
    def show_all_goods(self):
        sql = 'select * from goods'
        self.excute_sql(sql)
    # 查询所有的商品种类
    def show_all_cates(self):
        sql = 'select * from goods_cates'
        self.excute_sql(sql)

    # 查询所有的品牌,并进行去重
    def show_all_brands(self):
        sql = 'select distinct brand_name from goods'
        self.excute_sql(sql)

    # 添加商品分类
    def add_cate(self):
        name = input('请输入商品分类名字:')
        # 要注意 value 后跟的是字符串,格式化字符串后得到数据不带引号,要在格式化字符串的时候加上引号
        # f"-- insert into goods_cates (name) value (商品信息)"
        sql = f"insert into goods_cates (name) value ('{
      
      name}')"
        self.excute_sql(sql)
        # 提交事务
        self.conn.commit()
    # 单独定义函数,执行sql语句,减少重复代码
    def excute_sql(self,sql):
        self.cs.execute(sql)
        res = self.cs.fetchall()
        for data in res:
            print(data)
    # 自动关闭连接
    def __del__(self):
        self.conn.commit()

def main():
    shop = Shopping()
    shop.run()
if __name__ == '__main__':
    main()

Import the library, build the framework of the code, create the shopping class, define the main function, and establish the entry of the main program. When instantiating the object and initializing it, connect to the database and obtain the cursor object. Create an input template for the user to make a selection, prompt the user to enter the module, and prompt the user to input. You can use whlie True to enter an endless loop state and keep inputting. Judging whether the received user's input is 1-4, making judgments and executing different codes respectively. The self of the input template function has nothing to do with a series of prints. You can take out the content of the prints separately, use the decorator of the static method, define a function without any parameters in it, and call this function in while True. Define the function of querying all commodities, create a query, execute the sql statement, get all the results, and traverse the loop to get the data. Then define all product types, query all brands, execute sql statements in the function, obtain all results, and traverse the loop content are all repeated. You can package the repeated content separately, and define functions separately to execute sql statements. Then call this method in each function. According to the content entered by the user, these functions are called respectively.

view

A view (view) is a virtual table that is basically transparent to users who use the view. The view does not actually exist in the database. The row and column data come from the table used in the query of the custom view, and are in Generated dynamically when using the view.

  1. define viewcreate view 视图名称 as select 语句;
  2. View the view, when viewing the table, the view table page will be listedshow tables;
  3. use viewselect * from v_pro;
  4. delete viewdrop view 视图名称

The role of the view:

  • Simple: Improves reusability, just like a function, avoiding repeated writing of code
  • Security: The security performance has been improved, and different views can be set for different users. For example, the salary of the company is not allowed to be viewed by others, and a view without salary can be built for employees to view
  • Data independence: Once the structure of the view is determined, the impact of table structure changes on users can be shielded. Adding columns to the source table has no effect on the view; modifying the column names in the source table can be solved by modifying the view without causing any inconvenience to visitors. Influence
    insert image description here
    insert image description here
    insert image description here
    insert image description here

The following content appears, and the view cannot be modified.

  • The select clause contains distinct and group functions
  • The select statement contains group by, order by clauses and correlated subqueries
  • Multiple tables are included in the from clause
  • Cannot be updated if there are calculations in the view
  • If there is a column with a not-null constraint in the base table that does not appear in the view definition, the insert operation cannot be performed

Guess you like

Origin blog.csdn.net/hwwaizs/article/details/128722541