python操作mysql数据库增删改查的dbutils实例
python操作mysql数据库增删改查的dbutils实例
# 数据库配置文件
# cat gconf.py #encoding=utf-8
import json
# json里面的字典不能用单引号,一定要用双引号
USER_FILE='users.json' # mysql数据库连接信息
MYSQL_HOST = '192.168.3.91'
MYSQL_PORT = 3306
MYSQL_USER = 'root'
MYSQL_PASSWORD = 'root'
MYSQL_DB = 'cmdb'
MYSQL_CHARSET = 'utf8' # 邮件发送的信息
SMTP_SERVER_HOST='smtp.exmail.qq.com'
SMTP_SERVER_PORT=25
SMTP_USER='jack@qq.com'
# 邮箱客户端专用密码
SMTP_PWD='pass' # 接收邮件
ALARM_RECIVE = ['admin@163.com'] # app验证信息
APP_KEY = 'adI23SaE926DSslieo'
APP_SECRET = 'adI23SaE926DSslieo'
# 操作数据库增删改查的dbutils.py代码
#encoding=utf-8 import MySQLdb import gconf # 主类
class MysqlConnection(object):
def __init__(self, host, port, user, passwd, db, charset='utf8'):
self.__host = host
self.__port = port
self.__user = user
self.__passwd = passwd
self.__db = db
self.__charset = charset
self.__conn = None
self.__cur = None
self.__connect()
# 连接数据库
def __connect(self):
try:
self.__conn = MySQLdb.connect(host = self.__host, port = self.__port,\
user = self.__user, passwd = self.__passwd,\
db = self.__db, charset = self.__charset) self.__cur = self.__conn.cursor()
except BaseException as e:
print e def close(self):
# 在关闭连接之前将内存中的文件写入磁盘
self.commit()
if self.__cur:
self.__cur.close()
self.__cur = None if self.__conn:
self.__conn.close()
self.__conn = None
# 设置提交
def commit(self):
if self.__conn:
self.__conn.commit() def execute(self, sql, args = ()):
_cnt = 0
if self.__cur:
self.__cur.execute(sql, args)
return _cnt def fetch(self, sql, args = ()):
_cnt = 0
rt_list = []
# _cnt = self.execute(sql, args)
if self.__cur: _cnt = self.__cur.execute(sql, args)
rt_list = self.__cur.fetchall()
return _cnt, rt_list @classmethod
def execute_sql(cls, sql, args=(), fetch = True):
count = 0
rt_list = []
conn = MysqlConnection(host = gconf.MYSQL_HOST, port = gconf.MYSQL_PORT,\
user = gconf.MYSQL_USER, passwd = gconf.MYSQL_PASSWORD, db = gconf.MYSQL_DB,\
charset = gconf.MYSQL_CHARSET)
print sql
if fetch:
count, rt_list = conn.fetch(sql, args)
else:
count = conn.execute(sql, args)
conn.close()
print rt_list
return count, rt_list def execute_fetch_sql(sql, args = (), fetch = True):
return execute_sql(sql, args, fetch) def execute_commit_sql(sql, args = (), fetch = False):
return execute_sql(sql, args, fetch) # 区别在于是查询还是修改,增加,删除操作,用fetch来标识
def execute_sql(sql, args = (), fetch = True):
cur = None
conn = None
count = 0
rt = ()
try:
conn = MySQLdb.connect(host = gconf.MYSQL_HOST, port = gconf.MYSQL_PORT,\
user = gconf.MYSQL_USER, passwd = gconf.MYSQL_PASSWORD, db = gconf.MYSQL_DB,\
charset = gconf.MYSQL_CHARSET) cur = conn.cursor()
print 'dbutils sql:%s, args = %s' % (sql, args)
count = cur.execute(sql, args)
# 如果是查询
if fetch:
rt = cur.fetchall()
# if args:
# rt = cur.fetchone()
# else:
# rt = cur.fetchall()
else:
conn.commit() except BaseException, e:
print e
finally:
if cur:
cur.close()
if conn:
conn.close()
print 'dbutils:%s,%s' %(count,rt)
return count,rt # 批量插入数据库
def batch_execute_sql(sql, rt_list = []):
cur = None
conn = None
count = 0
rt = () try:
conn = MySQLdb.connect(host = gconf.MYSQL_HOST, port = gconf.MYSQL_PORT,\
user = gconf.MYSQL_USER, passwd = gconf.MYSQL_PASSWORD, db = gconf.MYSQL_DB,\
charset = gconf.MYSQL_CHARSET) cur = conn.cursor()
print sql
# 循环执行插入语句,一次性全部提交
for line in rt_list:
count += cur.execute(sql, line)
conn.commit() except BaseException, e:
print e
finally:
if cur:
cur.close()
if conn:
conn.close() return count # 测试代码
if __name__ == '__main__':
# conn = MysqlConnection(host = gconf.MYSQL_HOST, port = gconf.MYSQL_PORT,\
# user = gconf.MYSQL_USER, passwd = gconf.MYSQL_PASSWORD, db = gconf.MYSQL_DB,\
# charset = gconf.MYSQL_CHARSET) # # conn.execute('insert into user(username) values(%s)', ('jack123',))
# cnt, rt_list = conn.fetch('select * from user')
# print cnt,rt_list
# conn.close()
count, rt_list = MysqlConnection.execute_sql('insert into user(username) values(%s)',('tomkeeper',))
print rt_list
python操作mysql数据库增删改查的dbutils实例的更多相关文章
- Asp.Net操作MySql数据库增删改查
Asp.Net操作MySql数据库增删改查,话不多说直接步入正题.git源码地址:https://git.oschina.net/gxiaopan/NetMySql.git 1.安装MySQL数据库 ...
- Python实现mysql数据库增删改查
利用python操作mysql数据库用法简单,环境配置容易,本文将实现对库增.删.改.查的简易封装! 1. 环境配置 安装第三方包 ,导入模块 mysql.connector pip inst ...
- python2.7入门---操作mysql数据库增删改查
Python 标准数据库接口为 Python DB-API,Python DB-API为开发人员提供了数据库应用编程接口.Python 数据库接口支持非常多的数据库,你可以选择适合你项目的数据库: G ...
- Golang原生sql操作Mysql数据库增删改查
Golang要操作mysql数据库,首先需要在当期系统配置GOPATH,因为需要使用go get命令把驱动包下载到GOPATH下使用. 首先配置好你的GOPATH,执行以下命令,下载安装mysql驱动 ...
- python3操作mysql数据库增删改查
#!/usr/bin/python3 import pymysql import types db=pymysql.connect("localhost","root&q ...
- python操作mysql之增删改查
[insert] import MySQLdb conn = MySQLdb.connect(","08day5" ) cur = conn.cursor() #把数据放 ...
- MySQL数据库(增删改查语句)
MySQL数据库(增删改查语句)一.登录数据库:----> mysql -uroot -proot;(对应用户名和密码)二.SQL语句: 数据定义语言DDL 用来定义数据库.表.列,关 ...
- Java连接MySQL数据库增删改查通用方法
版权声明:本文为博主原创文章,未经博主允许不得转载. Java连接MySQL数据库增删改查通用方法 运行环境:eclipse+MySQL 以前我们Java连接MySQL数据库都是一个数据库写一个类,类 ...
- jsp-2 简单的servlet连接mysql数据库 增删改查
连接mysql数据库的操作 有增删改查 用的包有 commons-lang3-3.5 mysql-connector-java-5.1.40-bin 但是实际上也就是 数据查询和数据处理两种 所以对数 ...
随机推荐
- Expressions versus statements in JavaScript
Statements and expressions An expression produces a value and can be written wherever a value is exp ...
- java使用google开源工具实现图片压缩【转】
jar包名 import net.coobird.thumbnailator.Thumbnails; import net.coobird.thumbnailator.geometry.Positio ...
- centos下问题:connect:network is unreachable
问题描述 弄了三台机器准备搭建一个集群,按照centos7系统,一台主节点安装桌面环境,两台计算节点.配置计算节点的时候,发现ping不通,出现connect:network is unreachab ...
- vue中axios 配置请求拦截功能 及请求方式如何封装
main.js 中: import axios from '................/axios' axios.js 中: //axios.js import Vue from 'vue' i ...
- redis整合Spring集群搭建及业务中的使用
1.redis安装 Redis是c语言开发的. 安装redis需要c语言的编译环境.如果没有gcc需要在线安装.yum install gcc-c++ 安装步骤: 第一步:redis的源码包上传到li ...
- request和reponse
- oracle 存储过程(包)的写法和执行
--in 代表输入参数,out 代表输出参数create or replace procedure myproc(id in int, v_message out varchar2) is--定义临时 ...
- 导弹拦截 dp
n∗lognn*lognn∗logn写法,lis[i]的意义为:所有最长上升子序列长度为i的位置上的最小a数组元素值lis[i]的意义为:所有最长上升子序列长度为i的位置上的最小a数组元素值lis[i ...
- Tomcat清理日志文件无法立即释放磁盘空间
1 自己删除了Tomcat的日志文件,但是依然显示磁盘百分百占用 进入Tomcat目录显示日志已经删除 查询磁盘空间依旧百分百占用 2 自己杀死Tomcat进程然后重启,成功释放空间 3 原因,通过网 ...
- byte数组和int之间相互转化的方法
Java中byte数组和int类型的转换,在网络编程中这个算法是最基本的算法,我们都知道,在socket传输中,发送者接收的数据都是byte数组,但是int类型是4个byte组成的,如何把一个整形in ...