您的位置:首页 > 博客中心 > 数据库 >

python链接数据库pymysql

时间:2022-03-15 10:48

#python链接数据库pymysql

import pymysql

config = {‘host‘ : ‘172.0.0.1‘,
          ‘user‘ : ‘lijing‘,
          ‘post‘ : ‘123456‘}
#链接数据库
db = pymysql.connect(**config)
#获取游标
cursor = db.cursor()

try:
    #执行sql命令
    sql = "create table if not exists 表名"
    cursor.execute(sql)
    
    #获取返回的结果一条
    cursor.fetchone()
    #获取返回结果3条
    cursor.fetchmany(3)
    #获取返回结果全部
    cursor.fetchall()

    #提交到数据库执行
    db.commit()
except Exception as e:
    raise e
    #回滚
    db.rollback()
finally:
    #关闭游标
    cursor.close()
    #关闭数据库链接
    db.close()

 

本类排行

今日推荐

热门手游