使用pymysql:
//安装pymysql
pip install pymysql

代码:

# coding=utf8

import pymysql

# 创建连接对象
conn = pymysql.connect(host='127.0.0.1', user='root', password='', db='school')

# 创建游标
cur = conn.cursor()

# 查询数据库里某张表的内容
def get_table():
    cur.execute('SELECT name, address FROM teacher')
    r = cur.fetchall()

    print(r)

#get_table()

# 执行sql,查询单条数据,并返回受影响行数
effect_row = cur.execute("update teacher set name='alice' where id=1")

#print(effect_row)
#get_table()

# 插入多条,并返回受影响的条数
effect_rows = cur.executemany("insert into teacher(name, address)values(%s, %s)",
                              [('aaa', 'a1'), ('bbb', 'b1'), ('ccc', 'c1')])

#print(effect_rows)
#get_table()

# 获取最新自增id
new_id = cur.lastrowid
#print(new_id)

# 查询数据
get_datas = cur.execute('SELECT * FROM teacher')
# 获取一行
#row_1 = cur.fetchone()
#print(row_1)
# 获取最多2行
#row_2 = cur.fetchmany(2)
#print(row_2)

row_3 = cur.fetchall()
print(row_3)

#重设游标为字典类型
cur = conn.cursor(cursor = pymysql.cursors.DictCursor)

#提交,保存新建或修改的数据
conn.commit()
# 关闭游标
cur.close()
# 关闭连接
conn.close()
04-26 14:14
查看更多