Python 封装MySQL类

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
简介:

  以后再也不用每次都重新写啦!

   

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import  MySQLdb
OperationalError  =  MySQLdb.OperationalError
class  MySQL:
     def  __init__( self ,host,user,password,port = 3306 ,charset = "utf8" ):
         self .host = host
         self .port = port
         self .user = user
         self .password = password
         self .charset = charset
         try :
             self .conn = MySQLdb.connect(host = self .host,port = self .port,user = self .user,passwd = self .password)
             self .conn.autocommit( False )
             self .conn.set_character_set( self .charset)
             self .cur = self .conn.cursor()
         except  MySQLdb.Error as e:
             print ( "Mysql Error %d: %s"  %  (e.args[ 0 ], e.args[ 1 ]))
                     
     def  __del__( self ):
         self .close()
                          
     def  selectDb( self ,db):
         try :
             self .conn.select_db(db)
         except  MySQLdb.Error as e:
             print ( "Mysql Error %d: %s"  %  (e.args[ 0 ], e.args[ 1 ]))
                          
     def  query( self ,sql):
         try :
             n = self .cur.execute(sql)
             return  n
         except  MySQLdb.Error as e:
             print ( "Mysql Error:%s\nSQL:%s"  % (e,sql))
                          
     def  fetchRow( self ):
         result  =  self .cur.fetchone()
         return  result
                          
     def  fetchAll( self ):
         result = self .cur.fetchall()
         desc  = self .cur.description
         =  []
         for  inv  in  result:
             _d  =  {}
             for  in  range ( 0 , len (inv)):
                 _d[desc[i][ 0 ]]  =  str (inv[i])
                 d.append(_d)
         return  d
                          
     def  insert( self ,table_name,data):
         columns = data.keys()
         _prefix = "".join([ 'INSERT INTO `' ,table_name, '`' ])
         _fields = "," .join(["".join([ '`' ,column, '`' ])  for  column  in  columns])
         _values = "," .join([ "%s"  for  in  range ( len (columns))])
         _sql = " ".join([_prefix," ( ",_fields," ) VALUES ( ",_values," )"])
         _params = [data[key]  for  key  in  columns]
         return  self .cur.execute(_sql, tuple (_params))
                        
     def  update( self ,tbname,data,condition):
         _fields = []
         _prefix = "".join([ 'UPDATE `' ,tbname, '`' , 'SET' ])
         for  key  in  data.keys():
             _fields.append( "%s = %s"  %  (key,data[key]))
         _sql = " ".join([_prefix ,_fields, " WHERE", condition ])
                            
         return  self .cur.execute(_sql)
                        
     def  delete( self ,tbname,condition):
         _prefix = "".join([ 'DELETE FROM  `' ,tbname, '`' , 'WHERE' ])
         _sql = "".join([_prefix,condition]) 
         return  self .cur.execute(_sql)
                          
     def  getLastInsertId( self ):
         return  self .cur.lastrowid
                          
     def  rowcount( self ):
         return  self .cur.rowcount
                          
     def  commit( self ):
         self .conn.commit()
                        
     def  rollback( self ):
         self .conn.rollback()
                          
     def  close( self ):
         self .cur.close()
         self .conn.close()
                            
if  __name__ = = '__main__' :
     n = MySQL( '127.0.0.1' , 'root' , '123456' , 3306 )
     n.selectDb( 'test' )
     tbname = 'map'
     a = ({ 'id' : 3 , 'x' : 3 , 'y' : 3 },{ 'id' : 4 , 'x' : 4 , 'y' : 4 },{ 'id' : 5 , 'x' : 5 , 'y' : 5 })
     for  in  a:
         n.insert(tbname,d)
     n.commit()


 一个重量级的MySQL-Python 封装类:facebook python mysql






本文转自 位鹏飞 51CTO博客,原文链接:http://blog.51cto.com/weipengfei/1269034,如需转载请自行联系原作者

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助     相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
1天前
|
Python
Python-类视图和蓝图
Python-类视图和蓝图
9 2
|
1天前
|
存储 Java 数据安全/隐私保护
Python----类对象和实例对象
Python----类对象和实例对象
9 2
|
2天前
|
C++ Python
Python中的类与对象
Python中的类与对象
6 1
|
2天前
|
Python
在Python中,类的属性可以分为公有属性和私有属性
【5月更文挑战第7天】Python类包含公有和私有属性。公有属性可直接外部访问,如`person.name`,而私有属性如`_name`需通过getter/setter方法访问,如`person.getName()`和`person.setName()`。私有属性用于封装数据、隐藏实现细节,增强代码可维护性和安全性。封装能灵活修改内部实现,不影响外部;安全性防止外部非法修改数据;一致性确保所有数据操作在类内完成,简化代码并减少错误。
28 10
|
2天前
|
Python
【Python 基础】Python中的实例方法、静态方法和类方法有什么区别?
【5月更文挑战第6天】【Python 基础】Python中的实例方法、静态方法和类方法有什么区别?
|
2天前
|
存储 程序员 Python
Python中自定义类实例化数组的艺术
Python中自定义类实例化数组的艺术
9 1
|
2天前
|
程序员 Linux C++
Python中的WinForms类桌面应用程序开发
Python中的WinForms类桌面应用程序开发
25 4
|
2天前
|
Java 开发者 索引
Python基础语法:类笔记
本篇博文是把自己在学习python类的过程中自己理解和笔记,一点一点总结的写出出来,做一个总结,加深对面向对象编程的理解。
|
2天前
|
数据可视化 索引 Python
数据分享|Python用PyMC3贝叶斯模型平均BMA:采样、信息准则比较和预测可视化灵长类动物的乳汁成分数据
数据分享|Python用PyMC3贝叶斯模型平均BMA:采样、信息准则比较和预测可视化灵长类动物的乳汁成分数据
|
2天前
|
SQL 关系型数据库 MySQL
使用Python的pymysql库连接MySQL,执行CRUD操作
使用Python的pymysql库连接MySQL,执行CRUD操作:安装pymysql,然后连接(host='localhost',user='root',password='yourpassword',database='yourdatabase'),创建游标。查询数据示例:`SELECT * FROM yourtable`;插入数据:`INSERT INTO yourtable...`;更新数据:`UPDATE yourtable SET...`;删除数据:`DELETE FROM yourtable WHERE...`。
29 0

推荐镜像

更多