python数据库建表_python操作数据库类。实现建表、插入数据、查询数据功能

1 importmysql.connector2 classdatabase:3 def __init__(self,ip,port,user,psw,dbname):4

5 try:6 con=mysql.connector.connect(7 host=ip,8 user=user,9 password=psw,10 port=port,11 database=dbname,12 charset='utf8',13 buffered=True14 )15 print('数据库连接成功')16 self.con=con #con在其他类方法中还要多次调用,所以定义为成员变量

17 #cursor=con.cursor()

18 exceptmysql.connector.Error as e:19 print('连接失败',str(e))20

21 defcreate_tb(self,sql):22 try:23 cursor=self.con.cursor()#获取游标

24 cursor.execute(sql)#执行sql

25 print('创建成功')26 exceptmysql.connector.Error as e:27 print('创建失败',str(e))28 finally:29 cursor.close()#关闭游标

30

31 definsert_tb(self,sql,data):32 try:33 cursor=self.con.cursor()34 cursor.executemany(sql,data)35 self.con.commit()36 print('数据插入成功')37 exceptmysql.connector.Error as e:38 self.con.rollback()39 print('插入失败',str(e))40 cursor.close()41

42 defselect_tb(self,sql):43 try:44 cursor=self.con.cursor(dictionary=True)45 cursor.execute(sql)46 result1=cursor.fetchall()47 print('查询全部结果:',result1)48 exceptmysql.connector.Error as e:49 print('查询失败',str(e))50 finally:51 cursor.close()52

53 defselect_tb_one(self,sql):54 try:55 cursor=self.con.cursor(dictionary=True)56 cursor.execute(sql)57 result2=cursor.fetchone()58 print('查询一条结果:',result2)59 exceptmysql.connector.Error as e:60 print('查询失败',str(e))61 finally:62 cursor.close()63

64 defselect_tb_many(self,sql,count):65 try:66 cursor=self.con.cursor(dictionary=True)67 cursor.execute(sql)68 result3=cursor.fetchmany(count)69 print('查询结果:',result3)70 exceptmysql.connector.Error as e:71 print('查询失败',str(e))72 finally:73 cursor.close()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值