# -*- coding:utf-8 -*- import pymysql # 1. 链接数据库 db = pymysql.connect( # 链接的数据库的host主机地址:默认本地数据库使用localhost或者127.0.0.1,如果是 # 远程数据库,需要设置为主机的ip地址 host = 'localhost', # 链接数据库的用户名 user = 'root', # 连接数据库的密码 password = '123456', # 端口号 3303 musql数据库的默认端口 # 80端口 http协议的默认端口 # 443端口 https协议的默认端口 port = 3306, # 连接数据库的名称 db = 'student', # 如果数据库中需要写入中文,需要配置以下两个参数 # use_unidode = True, # charset = 'utf-8' ) # 2.获取游标 cursor = db.cursor() # 3. 准备sql语句 # create_table = 'CREATE TABLE IF NOT EXISTS stu(id INTEGER PRIMARY KEY ,name TEXT,age INTEGER )' # 4. 执行sql语句 # cursor.execute(create_table) #-------------------------------------------------------- # 向数据库中插入数据 insert_sql = "INSERT INTO stu(id,name,age)VALUE (3,'zhangsan',22)" cursor.execute(insert_sql) # #-------------------------------------------------------- # # 修改数据 # update_sql = "UPDATE stu SET age=50 WHERE id = 2" # cursor.execute(update_sql) # #-------------------------------------------------------- # # 删除数据库中数据 # delete_sql = "DELETE FROM stu WHERE id = 3" # cursor.execute(delete_sql) # #-------------------------------------------------------- # 查询数据库中的数据 select_sql = "SELECT * FROM stu" res = cursor.execute(select_sql) # fetchall() 查询所有数据 res = cursor.fetchall() print(res) # 需要重新执行查询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() # ========================================================= # 同步写入数据,阻塞 # 异步写入数据,非阻塞
基于python的-mysql基本用法
最新推荐文章于 2022-07-24 11:11:35 发布