pymysql连接数据库,实现数据库增删改查

Python MySQL数据库操作指南
本文详细介绍了使用Python的pymysql库进行数据库操作的方法,包括数据库的连接与断开、数据的增删改查,以及批量操作和创建表的SQL语句。通过具体的代码示例,读者可以学习如何在Python中高效地管理和操作MySQL数据库。

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

 

转载于:https://www.cnblogs.com/apollo1616/p/10268874.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值