PyMySQL基本用法

# mysql-python  python2中使用这个包支持python操作mysql
# python pymysql操作mysql数据库

import pymysql


# 1.链接数据库
db = pymysql.connect(
    # 链接的数据库的host主机地址:默认本地数据库使用localhost或者127.0.0.1,如果是远程数据库,需要设置为主机的ip地址
    host = 'localhost',
    # 链接数据库的用户名
    user = 'root',
    # 链接数据库的密码
    password = '123456',
    # 端口号 3306 mysql数据库的默认端口
    # 80端口  http协议的默认端口
    # 443端口 https协议的默认端口
    port = 3306,
    # 链接的数据库的名称
    db = 'student',
    # 如果数据库中需要写入中文,配置以下两个参数
    use_unicode =True,
    charset='utf8'
)

# 2.获取游标
cursor = db.cursor()
# 1.准备sql语句.创建表
# AUTO_INCREMENT 自增
# PRIMARY KEY 设置为主键
create_table = 'CREATE TABLE IF NOT EXISTS stu(id INTEGER PRIMARY KEY AUTO_INCREMENT,name Text,age INTEGER )'
# 执行sql语句
cursor.execute(create_table)

# 3.向数据库中插入数据
# insert_sql = "INSERT INTO stu(id,name,age)VALUE (3,'张三',22)"
# # 执行sql语句
# cursor.execute(insert_sql)
# 提交操作
# db.commit()

# 4.修改数据库中的数据
# update_sql = "UPDATE stu SET age=50 WHERE id = 2"
# cursor.execute(update_sql)

# 5.删除数据库中数据
# delete_sql = "DELETE FROM stu WHERE id = 3"
# cursor.execute(delete_sql)

# 6.查询数据库中的数据
select_sql = "SELECT * FROM stu"
res = cursor.execute(select_sql)
# 和sqlite3有区别
# 查询所有的数据
# res = cursor.fetchall()

需要重新执行查询sql语句,然后再使用fetchone查询一条数据
# select_sql = "SELECT * FROM stu"
# res = cursor.execute(select_sql)
# res = cursor.fetchone()
# fetchmany() 获取指定条数的数据
res = cursor.fetchmany(4)
for id,name,age in res:
    print(id,name,age)

提交操作
db.commit()

关闭游标
cursor.close()
关闭数据库
db.close()


你可能感兴趣的:(数据库,PyMSQL)