python连接MySQL

时间:2022-03-17 06:21:51

python连接MySQL  

# 下载第三方模块: pip3 install pymysql

# 面条版
import pymysql  # 连接mysql数据库的模块

# 1.连接数据库
client = pymysql.connect(
    host=127.0.0.1,
    port=3306,
    user=root,
    password=123456,
    database=db4,
    charset=utf8,  # 此处不能写utf-8
    autocommit=True
)

# print(client)

# 2.获取游标对象 ----> 游标 可以用来提交sql命令
# 将取回值以字典形式显示:pymysql.cursors.DictCursor
cursor_obj = client.cursor(pymysql.cursors.DictCursor)
# cursor_obj = client.cursor()  # 以元组形式显示(1, ‘tank‘)

# 3.通过execute 可以提交sql语句

# 1)查数据
# sql = ‘select * from emp‘
# # 提交sql语句
# cursor_obj.execute(sql)
#
# # 4.提交后,通过cursor_obj对象.fetchall() 获取所以查询到的结果
# res = cursor_obj.fetchall()
# print(res)
#
# for dic in res:
#     print(dic)

# 2)插入数据
# 创建表
# sql = ‘create table user(id int, name varchar(16))‘

# sql = ‘insert into user(id, name) values(1, "tank")‘

# 3) 更新数据
# try:
#     sql = ‘update user set name="tank_is_handsome" where id=1‘
#     cursor_obj.execute(sql)
#
# except Exception as e:
#     print(e)

# 4) 删除数据
# sql = ‘delete from user‘
# cursor_obj.execute(sql)
#
# # 关闭游标
# cursor_obj.close()
#
# # 关闭客户端连接
# client.close()