11.Python列表推导式及数据库连接

1.列表推导式

  1. 列表推导式
a = [i for i in range(1, 10)]
print(a)
a = [i for i in range(1, 10) if i % 2 == 0]
print(a)
a = [(i, j) for i in range(1, 3) for j in range(1, 3)]
print(a)
a = [(i, j, k) for i in range(1, 3) for j in range(1, 3) for k in range(1, 3)]
print(a)

打印结果如下:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 4, 6, 8]
[(1, 1), (1, 2), (2, 1), (2, 2)]
[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2), (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]

  1. 集合类型


    11.Python列表推导式及数据库连接_第1张图片
    image.png

注意:使用set ,可以快速的完成对list中的元素去重复功能

2.连接数据库

# 首先得导入pymysql
import pymysql as pm

# 创建连接
coon = pm.connect("localhost", "root", "123456", "vhr")
# 增删改查
course = coon.cursor()
course.execute("SELECT * FROM role")
role = course.fetchone()
print(role)
roles = course.fetchall()
print(roles)
# 关闭数据库连接
coon.close()

一个数据库连接工具:mysql_util.py

import pymysql


class MysqlHelper(object):
    config = {"host": "localhost", "user": "root", "password": "123456", "db": "db_spring", "charset": "utf8"}

    def __init__(self):
        self.connection = None
        self.cursor = None

    def getOne(self, sql, *args):
        try:
            self.connection = pymysql.connect(**MysqlHelper.config)
            self.cursor = self.connection.cursor()
            self.cursor.execute(sql, args)
            return self.cursor.fetchone()
        except Exception as ex:
            print(ex, ex)
        finally:
            self.close()

    def getList(self, sql, *args):
        try:
            self.connection = pymysql.connect(**MysqlHelper.config)
            self.cursor = self.connection.cursor()
            self.cursor.execute(sql, args)
            return self.cursor.fetchall()
        except Exception as ex:
            print(ex, ex)
        finally:
            self.close()

    def executeDML(self, sql, *args):
        try:
            self.connection = pymysql.connect(**MysqlHelper.config)
            self.cursor = self.connection.cursor()
            self.cursor.execute(sql, args)
            new_id = self.connection.insert_id()
            self.connection.commit()
            return new_id
        except Exception as ex:
            print(ex, ex)
        finally:
            self.close()

    def close(self):
        if self.cursor:
            self.cursor.close()
        if self.connection:
            self.connection.close()


if __name__ == "__main__":
    helper = MysqlHelper()
    print(
        helper.executeDML("INSERT INTO user(username,password,enabled,locked) VALUES (%s,%s,%s,%s)", "王朝", "123456", 1,
                          1))

你可能感兴趣的:(11.Python列表推导式及数据库连接)