usr bin env python coding utf-8 import os sys cx_Oracle config class o

 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os, sys, cx_Oracle, config
class oracle_db:
def __init__(self): # подключение к БД
os.environ["NLS_LANG"] = "AMERICAN_AMERICA.CL8MSWIN1251"
if config.ORACLE_HOME != "":
os.environ["ORACLE_HOME"] = config.ORACLE_HOME
try:
self.db = cx_Oracle.connect("%s/%s@%s" % (config.DBLOGIN, config.DBPASSWD, config.DBNAME))
except:
raise "DatabaseError", "Can't connect to database (%s)" % str(sys.exc_value).strip()
self.cursor = self.db.cursor()
self.cursor.execute("ALTER SESSION SET NLS_DATE_LANGUAGE='RUSSIAN'")
# возвращает массив словарей, или оракловую ошибку
def fetchall(self, sql):
try:
self.cursor.execute(sql.decode("utf-8").encode("cp1251"))
except:
raise "DatabaseError", "Can't execute query (%s)" % str(sys.exc_value).strip()
result = []
for row in self.cursor.fetchall():
i = 0
dict = {}
for col in self.cursor.description:
if type(row[i]) == type(""):
dict[i] = row[i].decode("cp1251").encode("utf-8").strip()
else:
dict[i] = row[i]
i += 1
result.append(dict)
return result
# возвращает словарь, или оракловую ошибку
def fetchone(self, sql):
try:
self.cursor.execute(sql)
except:
raise "DatabaseError", "Can't execute query (%s)" % str(sys.exc_value).strip()
dict = {}
i = 0
row = self.cursor.fetchone()
if row == None: return None
for col in self.cursor.description:
if type(row[i]) == type(""):
dict[col[0]] = row[i].decode("cp1251").encode("utf-8")
else:
dict[col[0]] = row[i]
i += 1
return dict
def query(self, sql):
try:
self.cursor.execute(sql.decode("utf-8").encode("cp1251"))
except:
raise "DatabaseError", "Can't execute query (%s)" % str(sys.exc_value).strip()
def close(self):
self.cursor.close()
self.db.commit()
self.db.close()