python连接数据库

本文讲述了Python连接MySQL数据库的方法,包括基本操作如创建游标、执行SQL以及代码封装使用ini文件。还涉及了配置文件的使用和异常处理。
摘要由CSDN通过智能技术生成

一、基本操作

1.连接数据库

db = pymysql.connect(host='IP',port=3306,user='端口',password='密码',database='数据库名',charset='utf8')

2.创建游标,操作数据库;

  • 查询操作使用 游标.fetchone()然后print打印出来
cur=con.cursor() #创建游标
sql='select * from student3'
cur.execute(sql) #执行sql
reslut=cur.fetchone() #查询数据 fetchone():查询一条; fetchall():查询所有;fetchmany(指定数字):查询指定条数  
print(reslut)
db.close()
  • 增加、修改、删除等操作需要在执行sql后使用 db.commit()语句提交
cur=con.cursor() #创建游标
sql='delete from student3 where id=8'
cur.execute(sql) #执行sql
db.commit()
db.close()  #关闭连接

二、代码封装

  • ini文件

  • 代码封装,解析ini文件需要用到 configparser
import configparser
import pymysql
# 获取配置文件里面的数据 MySqlDB('db.ini','Test_db') 
class MySqlDB:
 
    # 读取配置文件里面的数据,在放到连接中连接数据库
    def __init__(self,configpath,db):  
        """
        解析ini配置文件,创建连接、创建游标
        :param configpath: ini文件路径
        :param db: ini文件中的哪个配置连接
        """
        config=configparser.ConfigParser()
        config.read(configpath)
        # 读取文件数据
        host=config[db]['host']
        port=int(config[db]['port'])
        user=config[db]['user']
        password=config[db]['password']
        database=config[db]['database']
        charset=config[db]['charset']
        #创建连接
        self.db=pymysql.connect(host=host, port=port, user=user, password=password, database=database,
                                  charset=charset)
        # 创建游标
        self.cur = self.db.cursor()
	
    #关闭连接、关闭游标
    def close(self):
        self.cur.close()
        self.db.close()

	#封装查询sql
    def get_all(self,sql):
        ret=None
        try:
            self.cur.execute(sql)
            ret=self.cur.fetchall()
            self.close()
        except Exception as e:
            print(e)
        return ret
  
	#封装编辑sql
    def edit(self,sql):
        try:
            self.cur.execute(sql)
            self.db.commit()
            self.close()
        except Exception as e:
            print(e)
        return True

if __name__ == '__main__':

    my = MySqlDB('db.ini','Test_db')
    print(my.get_all('select * from student3'))

  • 21
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吃鱿鱼的大叔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值