将降大任于是人也,必先苦其心志,劳其筋骨,饿其体肤,空乏其身,行拂乱其所为,所以动心忍性,曾益其所不能。天

时间在流逝,在不正经就晚咯

pymysql模块使用

 


一、写函数的原因

  写这个函数的原因就是为了能够不每次在用Python用数据库的时候还要在写一遍  做个通用函数做保留,也给大家做个小小的分享,函数不是最好的,希望有更好的代码的朋友能提出 互相学习

二、函数代码

  PS:代码是用Python3.6 写的

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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import pymysql
 
class mysql (object):
    def __init__(self, dbconfig):
        """
        初始化连接信息
        :param dbconfig: 连接信息的字典
        """
        self.host = dbconfig['host']
        self.port = dbconfig['port']
        self.user = dbconfig['user']
        self.passwd = dbconfig['passwd']
        self.db = dbconfig['db']
        self.charset = dbconfig['charset']
        self._conn = None
        self._connect()
        self._cursor = self._conn.cursor ()
 
    def _connect(self):
        """
        连接数据库方法
        :return:
        """
        try:
            self._conn = pymysql.connect (host=self.host, port=self.port, user=self.user, passwd=self.passwd,
                                          db=self.db, charset=self.charset)
        except pymysql.Error as e:
            print(e)
 
    def query(self, sql):
        try:
            result = self._cursor.execute (sql)
        except pymysql.Error as e:
            print(e)
            result = False
        return result
 
    def select(self, table, column='*', condition=''):
        """
        查询数据库方法
        :param table: 库里面的表
        :param column: 列字段
        :param condition: 条件语句 (where id=1)
        :return:
        """
        condition = ' where ' + condition if condition else None
        if condition:
            sql = "select %s from %s %s" % (column, table, condition)
            # print(sql)
        else:
            sql = "select %s from %s" %(column, table)
            # print(sql)
        self.query (sql)
        return self._cursor.fetchall()
 
 
    def insert(self,table,tdict):
        """
        插入数据库方法,replace去重插入  insert不去重插入
        :param table: 表名
        :param tdict: 要插入的字典
        :return:
        """
        column = ''
        value = ''
        for key in tdict:
            column += ',' + key
            value += "','" + tdict[key]
        column = column[1:]
        value = value[2:] + "'"
 
        sql = "replace into %s(%s) values(%s)" %(table,column,value)    # 去重
        # sql = "insert into %s(%s) values(%s)" %(table,column,value)   # 不去重
        self._cursor.execute(sql)
        self._conn.commit()
        return self._cursor.lastrowid
 
    def update(self,table,tdict,condition=''):
        """
        更新数据库方法
        :param table: 表名
        :param tdict: 更新数据库数据字典
        :param condition: 条件语句 (where id=1)
        :return:
        """
        if not condition:
            print('must have id')
            exit()
        else:
            condition = 'where ' + condition
        value = ''
        for key in tdict:
            value += ",%s='%s'" %(key,tdict[key])
        value = value[1:]
        sql = "update %s set %s %s" %(table,value,condition)
        # print(sql)
        self._cursor.execute(sql)
        self._conn.commit()
        return self.affected_num()
 
    def delete(self,table,condition=''):
        """
        删除方法
        :param table: 表名
        :param condition: 条件语句 (where id=1)
        :return:
        """
        condition = ' where ' + condition if condition else None
        sql = "delete from %s %s" %(table,condition)
        # print(sql)
        self._cursor.execute(sql)
        self._conn.commit()
        return self.affected_num()
 
    def all(self,*args):
        """
        可以执行所有的SQL语句 相当于登录到数据库执行,就是返回结果没有做处理 后期会更新
        :param args: SQL 语句(select * from ssh)
        :return:
        """
        sql = input("请输入SQL语句>>:")
        sql = "%s" %sql
        self._cursor.execute (sql)
        self._conn.commit ()
        return self._cursor.fetchall ()
 
 
    def rollback(self):
        """
        数据库的事务
        :return:
        """
        self._conn.rollback()
 
 
    def affected_num(self):
        """
        受影响的条数
        :return:
        """
        return self._cursor.rowcount
 
 
    def int_to_ip_or_ip_to_int(self,method,num,ip=''):
        """
        主要是对数据库的IP和数值之间的转换
        :param method: 转换方法两种(inet_ntoa,inet_aton)
        :param num: 数值
        :param ip: IP地址
        :return:
        """
        if method == 'inet_ntoa':
            sql = "select %s(%s)" %(method,num)
        elif method == 'inet_aton':
            sql = "select %s(%s)" %(method,ip)
        self.query(sql)
        return self._cursor.fetchall()
 
    def __del__(self):
        """
        关闭连接
        :return:
        """
        try:
            self._cursor.close ()
            self._conn.close ()
        except:
            pass
 
    def close(self):
        """
        关闭连接
        :return:
        """
        self.__del__ ()
 
 
# 函数的使用
if __name__ == '__main__':
    dbconfig = {
        'host': '192.168.163.129',      # MySQL地址
        'port': 3306,                          # 端口
        'user': 'root',                          # 用户名
        'passwd': '123456',                # 密码
        'db': 'com_hosts',                   # 数据库
        'charset': 'utf8',                     # 字符集
    }
    db = mysql (dbconfig)                # 初始化函数
     
    # 查询
    print(db.select ('ssh'))
    # 更新
    print(db.update('ssh', tdict, 'Id=2'))
    # 插入
    print(db.insert('ssh',tdict))
    # 删除
    print(db.delete('ssh','Id=6'))
 
    # 执行SQL语句
    while True:
        a = db.all()
        for i in a:
            print(i)
    db.close()

三、未实现功能(后续更新)

  其实代码的结果最好都是元祖,没有对结果进行数据格式化显示,后期会更新,大家用的时候根据需求对数据进行一些处理就好了,其实在公司是想写个MySQL的管理平台的,以后写好了会更新,也希望大家一起学习,可以QQ我

 

posted @   一本正经的搞事情  阅读(1995)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现

目录导航

点击右上角即可分享
微信分享提示