概述
连接数据库执行命令然后返回结果最后再断开连接,在写脚本时有时会经常做到,所以定义一个类
python连接MySQL
连接MySQL使用的包是pymysql
class cnMySQL: def __init__(self): self._dbhost = '172..16.56.2' self._dbuser = 'dba' self._dbpassword = 'dba1' self._dbname = 'test' self._dbcharset = 'utf8' self._dbport = int(3306) self._conn = self.connectMySQL() if (self._conn): self._cursor = self._conn.cursor(cursor=pymysql.cursors.DictCursor) def connectMySQL(self): try: conn = pymysql.connect(host=self._dbhost, user=self._dbuser, passwd=self._dbpassword, db=self._dbname, port=self._dbport, cursorclass=pymysql.cursors.DictCursor, charset=self._dbcharset) except Exception as e: raise #print("数据库连接出错") conn = False return conn def close(self): if (self._conn): try: if (type(self._cursor) == 'object'): self._conn.close() if (type(self._conn) == 'object'): self._conn.close() except Exception: print("关闭数据库连接异常") def ExecQuery(self,sql,*args): """ 执行查询语句 """ res = '' if (self._conn): try: self._cursor.execute(sql,args) res = self._cursor.fetchall() except Exception: res = False print("查询异常") self.close() return res
python连接PostgreSQL
连接PG使用的包是 psycopg2
class PGINFO: def __init__(self,host, user, pwd, db, port): self.host = host self.user = user self.pwd = pwd self.db = db self.port = port def __GetConnect(self): """ 得到连接信息 返回: conn.cursor() """ if not self.db: raise(NameError, "没有设置数据库信息") self.conn = psycopg2.connect(database=self.db, user=self.user, password=self.pwd, host=self.host, port=self.port) cur = self.conn.cursor() if not cur: raise (NameError, "连接数据库失败") else: return cur def ExecQuery(self, sql): """ 执行查询语句 """ if sql == 'close': self.conn.close() else: cur = self.__GetConnect() cur.execute(sql) # resList = cur.fetchall() return cur
先调用,这里调用是使用参数文件的
pg = PGINFO(host=host_cus, user=user_cus, pwd=pwd_cus, db=db_cus, port=port_cus)
执行命令,抓取返回结果
cur = pg.ExecQuery("show data_directory;") pgdata = cur.fetchone()
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/211953.html原文链接:https://javaforall.net
