1.数据库连接

# 创建连接
def create_conn():
    import pymysql
    conn = pymysql.connect(
        host='localhost',
        port=3306,
        user='root',
        password='root',
        database='py',
        charset='utf8'
    )
    # 得到一个可以执行SQL语句并且将结果作为字典返回的游标
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    return conn, cursor
# 关闭连接
def close_conn(conn, cursor):
    # 关闭光标对象
    cursor.close()
    # 关闭数据库连接
    conn.close()

 

2.增

# 单条插入数据
def InsertOneDB(sql, data):
    conn, cursor = create_conn()
    cursor.executemany(sql, data)
    conn.commit()
    close_conn(conn, cursor)

sqlInsertOneDB = "insert into user444 (name,age) values (%s,%s);"
data = [('john', 26)]
InsertOneDB(sqlInsertOneDB, data)
# 批量添加数据
def InsertManyDB(sql, data):
    conn, cursor = create_conn()
    cursor.executemany(sql, data)
    conn.commit()
    close_conn(conn, cursor)

data = [
    ('apollo', '28'),
    ('jack', '21'),
    ('merry', '29')
]
sql = 'insert into user444(name,age) values(%s,%s);'
InsertManyDB(sql, data)

 

3.删

# 删除数据
def DeleteOneDB(sql, data):
    conn, cursor = create_conn()
    print(sql)
    cursor.execute(sql, data)
    conn.commit()
    close_conn(conn, cursor)

# 定义将要执行的SQL语句
sql = "delete from user333 where name=%s;"
data = [("apollo11")]
DeleteOneDB(sql, data)

 

4.改

# 更改数据
def UpdataOneDB(sql, data):
    conn, cursor = create_conn()
    print(sql)
    cursor.execute(sql, data)
    conn.commit()
    close_conn(conn, cursor)

sql = "update user333 set name=%s where name=%s;"
data = ['Lily', 'jack11']
UpdataOneDB(sql, data)

 

5.查

# 查询数据
def SelectDB(sql, action, limit=None):
    conn, cursor = create_conn()
    cursor.execute(sql)
    if action == 'fetchone':
        ret = cursor.fetchone()  # 取一条
    elif action == 'fetchmany' and limit != None:
        ret = cursor.fetchmany(limit)  # 取三条
    else:
        ret = cursor.fetchall()  # 取全部
    for item in ret:
        print(item)
    close_conn(conn, cursor)


# 执行查询的sql语句
sql = "select name,age from user333;"
# action可选值:fetchone,fetchmany,fetchall
# fetchmany必须提供limit参数
action = 'fetchmany'
# 取数据库前3条数据
SelectDB(sql, action, 3)
# fetchall取所有数据
SelectDB(sql, action)
# fetchone取一条数据
SelectDB(sql, action)

 

6.创建表SQL

create table userinfo(
  id int auto_increment primary key ,
  name varchar(32) not null unique ,
  age int(2)
)engine =innodb default charset = utf8;
#注意:charset='utf8' 不能写成utf-8