包括python连接数据库,以及django下配置连接数据库

# -*- coding:utf-8 -*-
import psycopg2
import pymysql
import pymssql
import cx_Oracle import time
from functools import wraps
from contextlib import contextmanager # 测试一个函数的运行时间,使用方式:在待测函数直接添加此修饰器
def timethis(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
r = func(*args, **kwargs)
end = time.perf_counter()
print('\n============================================================')
print('{}.{} : {}'.format(func.__module__, func.__name__, end - start))
print('============================================================\n')
return r
return wrapper # 测试一段代码运行的时间,使用方式:上下文管理器with
# with timeblock('block_name'):
# your_code_block...
@contextmanager
def timeblock(label='Code'):
start = time.perf_counter()
try:
yield
finally:
end = time.perf_counter()
print('==============================================================')
print('{} run time: {}'.format(label, end - start))
print('==============================================================') class SqlConn():
'''
连接数据库,以及进行一些操作的封装
'''
sql_name = ''
database = ''
user = ''
password = ''
port = 0
host = '' # 创建连接、游标
def __init__(self, *args, **kwargs):
if kwargs.get("sql_name"):
self.sql_name = kwargs.get("sql_name")
if kwargs.get("database"):
self.database = kwargs.get("database")
if kwargs.get("user"):
self.user = kwargs.get("user")
if kwargs.get("password"):
self.password = kwargs.get("password")
if kwargs.get("port"):
self.port = kwargs.get("port")
if kwargs.get("host"):
self.host = kwargs.get("host") if not (self.host and self.port and self.user and
self.password and self.database):
raise Warning("conn_error, missing some params!") sql_conn = {'mysql': pymysql,
'postgresql': psycopg2,
'sqlserver': pymssql,
'orcle': cx_Oracle
} self.conn = sql_conn[self.sql_name].connect(host=self.host,
port=self.port,
user=self.user,
password=self.password,
database=self.database,
)
self.cursor = self.conn.cursor()
if not self.cursor:
raise Warning("conn_error!") # 测试连接
def test_conn(self):
if self.cursor:
print("conn success!")
else:
print('conn error!') # 单条语句的并提交
def execute(self, sql_code):
self.cursor.execute(sql_code)
self.conn.commit() # 单条语句的不提交
def execute_no_conmmit(self, sql_code):
self.cursor.execute(sql_code) # 构造多条语句,使用%s参数化,对于每个list都进行替代构造
def excute_many(self, sql_base, param_list):
self.cursor.executemany(sql_base, param_list) # 批量执行(待完善)
def batch_execute(self, sql_code):
pass # 获取数据
def get_data(self, sql_code, count=0):
self.cursor.execute(sql_code)
if int(count):
return self.cursor.fetchmany(count)
else:
return self.cursor.fetchall() # 更新数据
def updata_data(self, sql_code):
self.cursor(sql_code) # 插入数据
def insert_data(self, sql_code):
self.cursor(sql_code) # 滚动游标
def cursor_scroll(self, count, mode='relative'):
self.cursor.scroll(count, mode=mode) # 提交
def commit(self):
self.conn.commit() # 回滚
def rollback(self):
self.conn.rollback() # 关闭连接
def close_conn(self):
self.cursor.close()
self.conn.close()

python

import psycopg2
import pymysql
import pymssql
import cx_Oracle
from mysite.settings import DATABASES class SqlConn():
'''
连接数据库,以及进行一些操作的封装
''' # 创建连接、游标
def __init__(self):
print(DATABASES['default']['ENGINE'])
if DATABASES['default']['ENGINE'] == 'django.db.backends.mysql':
self.sql_name = 'mysql'
elif DATABASES['default']['ENGINE'] == 'sql_server.pyodbc':
self.sql_name = 'sqlserver'
print(self.sql_name)
else:
self.sql_name = ''
raise Warning("conn_error!")
self.host = DATABASES['default']['HOST']
self.port = DATABASES['default']['PORT']
self.user = DATABASES['default']['USER']
self.password = DATABASES['default']['PASSWORD']
self.database = DATABASES['default']['NAME'] sql_conn = {'mysql': pymysql,
'postgresql': psycopg2,
'sqlserver': pymssql,
'orcle': cx_Oracle
} self.conn = sql_conn[self.sql_name].connect(host=self.host,
port=self.port,
user=self.user,
password=self.password,
database=self.database,
# charset='utf8',
)
self.cursor = self.conn.cursor()
if not self.cursor:
raise Warning("conn_error!") # 测试连接
def test_conn(self):
if self.cursor:
print("conn success!")
else:
print('conn error!') # 单条语句的并提交
def execute(self, sql_code):
self.cursor.execute(sql_code)
self.conn.commit() # 单条语句的不提交
def execute_no_conmmit(self, sql_code):
self.cursor.execute(sql_code) # 构造多条语句,使用%s参数化,对于每个list都进行替代构造
def excute_many(self, sql_base, param_list):
self.cursor.executemany(sql_base, param_list) # 批量执行(待完善)
def batch_execute(self, sql_code):
pass def get_headers(self, table_name):
sql_code = "select COLUMN_NAME from information_schema.COLUMNS \
where table_name = '%s' and table_schema = '%s';" % (
table_name, self.database)
self.execute(sql_code)
return self.cursor.fetchall() # 获取数据
def get_data(self, sql_code, count=0):
print(sql_code)
# sql_code = 'select employee.pin,employee.emp_name,iclock.sn,area.area_name from transaction, employee, iclock, area where transaction.employee_id=employee.id and transaction.iclock_id=iclock.id and iclock.area_id=area.id;'
self.cursor.execute(sql_code)
if int(count):
return self.cursor.fetchmany(count)
else:
return self.cursor.fetchall() def get_headers_datas(self, sql_code, count=0):
self.cursor.execute(sql_code)
headers = []
for each in self.cursor.description:
headers.append(each[0])
if int(count):
return headers, self.cursor.fetchmany(count)
else:
return headers, self.cursor.fetchall() # 更新数据
def updata_data(self, sql_code):
self.cursor(sql_code) # 插入数据
def insert_data(self, sql_code):
self.cursor(sql_code) # 滚动游标
def cursor_scroll(self, count, mode='relative'):
self.cursor.scroll(count, mode=mode) # 提交
def commit(self):
self.conn.commit() # 回滚
def rollback(self):
self.conn.rollback() # 关闭连接
def close_conn(self):
self.cursor.close()
self.conn.close()

django

python连接mysql、sqlserver、oracle、postgresql数据库的一些封装的更多相关文章

  1. Hibernate 连接MySQL/SQLServer/Oracle数据库的hibernate.cfg.xml文件

    用Hibernate配置连接数据库可以方便我们对POJO的操作,节省了很多时间和代码.下面就分别说明连接不同数据库需要在hibernate.cfg.xml做的配置. 需要数据库驱动包可以点击这里下载: ...

  2. python连接mysql、oracle小例子

    import  MySQLdbimport  cx_Oracle   as  oraimport  pandas  as  pdfrom    sqlalchemy import create_eng ...

  3. mysql / sqlserver / oracle 常见数据库分页

    空闲时间里用着mysql学习开发测试平台和测试用具, 在公司里将可用的测试平台部署,将数据库换成sqlserver 巴望着能去用oracle的公司 mysql中的分页 limit是mysql的语法se ...

  4. python入门(十七)python连接mysql数据库

    mysql 数据库:关系型数据库mysql:互联网公司 sqllite:小型数据库,占用资源少,手机里面使用oracle:银行.保险.以前外企.sybase:银行+通信 互联网公司key:valuem ...

  5. python 连接Mysql数据库

    1.下载http://dev.mysql.com/downloads/connector/python/ 由于Python安装的是3.4,所以需要下载下面的mysql-connector-python ...

  6. Jsp 连接 mySQL、Oracle 数据库备忘(Windows平台)

    Jsp 环境目前最流行的是 Tomcat5.0.Tomcat5.0 自己包含一个 Web 服务器,如果是测试,就没必要把 Tomcat 与 IIS 或 Apache 集成起来.在 Tomcat 自带的 ...

  7. Python连接MySQL数据库的多种方式

    上篇文章分享了windows下载mysql5.7压缩包配置安装mysql 后续可以选择 ①在本地创建一个数据库,使用navicat工具导出远程测试服务器的数据库至本地,用于学习操作,且不影响测试服务器 ...

  8. Python 使用PyMySql 库 连接MySql数据库时 查询中文遇到的乱码问题(实测可行) python 连接 MySql 中文乱码 pymysql库

    最近所写的代码中需要用到python去连接MySql数据库,因为是用PyQt5来构建的GUI,原本打算使用PyQt5中的数据库连接方法,后来虽然能够正确连接上发现还是不能提交修改内容,最后在qq交流群 ...

  9. pymysql模块使用---Python连接MySQL数据库

    pymysql模块使用---Python连接MySQL数据库 浏览目录 pymysql介绍 连接数据库 execute( ) 之 sql 注入 增删改查操作 进阶用法 一.pymysql介绍 1.介绍 ...

  10. python连接MySQL/redis/mongoDB数据库的简单整理

    python连接mysql 用python操作mysql,你必须知道pymysql 代码示意: import pymysql conn = pymysql.connect(host='127.0.0. ...

随机推荐

  1. luogu P1084 疫情控制

    传送门 首先,所有军队又要尽量往上走,这样才能尽可能的封锁更多的到叶子的路径 而随着时间的增加,能封锁的路径也就越来越多,所以可以二分最终的时间 然后对于每个时间,就让能走到根的军队走到根,记录到根上 ...

  2. [转]Linux/Windows下脚本对拍程序

    [新]简单写法 (转载自:https://blog.csdn.net/ylsoi/article/details/79824655) 要求:文件输入输出,且输入输出文件需要对应 Linux: #inc ...

  3. Activity生命周期详解

    http://blog.csdn.net/liuhe688/article/details/6733407 onPause 回到 onResume 的过程“在一般的开发中用不上”,但是作为开发者还是有 ...

  4. ASP.NET MVC + EF 更新的几种方式(超赞)

    1.常用 db.Entry(实体).State = EntityState.Modified;db.SaveChanges(); 2.指定更新 db.Configuration.ValidateOnS ...

  5. svn数据库自动备份脚本

    创建一个存放备份数据的路径 mkdir /data/svnbak -p 采用shell脚本的方式实现自动备份 #vim backup.sh #!/bin/bash log="/data/sv ...

  6. sqlserver2008r2通过发布和订阅的方式进行数据库同步

    发布服务器:192.168.8.16 订阅服务器:192.168.8.92 发布服务器配置: 选择需要发布的数据库,这里是Attendace_new 订阅服务器配置: 在订阅服务器上新建一个数据库:d ...

  7. Ex 6_19 至多用k枚硬币兑换价格_第七次作业

    子问题定义: 定义一个二维数组b,其中b[i][j]表示用i个硬币是否能兑换价格j,表示第i个币种的面值, 递归关系: 初值设定: 求解顺序: 按下标从小到大依次求解数组b每一列的值,最后二维数组b的 ...

  8. GitHub上优秀的Go开源项目

    近一年来,学习和研究Go语言,断断续续的收集了一些比较优秀的开源项目,这些项目都非常不错,可以供我们学习和研究Go用,从中可以学到很多关于Go的使用.技巧以及相关工具和方法.我把他们整理发出来,大家有 ...

  9. Vue.js+Koa2移动电商实战 笔记

    地址:http://jspang.com/ https://github.com/shenghy/SmileVue 1.vant  https://www.youzanyun.com/zanui/va ...

  10. python下图像读取方式以及效率对比

    https://zhuanlan.zhihu.com/p/30383580 opencv速度最快,值得注意的是mxnet的采用多线程读取的方式,可大大加速