Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def deleteusage(self, target):
connection = psycopg2.connect(user=self.settings.dbuser,
password=self.settings.dbpass,
host=self.settings.dbhost,
port=self.settings.dbport,
database=self.settings.udrdb)
cursor = connection.cursor()
postgreSQL_delete_Query = "delete from usage where " \
"account like '{}'".format(target)
cursor.execute(postgreSQL_delete_Query)
connection.commit()
count = cursor.rowcount
print(count, "usage records deleted successfully ")
cursor.close()
connection.close()
def KMeansbySelectedTractid(nClusters, years, stateid, metroid, countyid, codestring, allcodestring, control):
#codes = [] # from control[[code, numerator, denominator, formula, shortname], ...]
codes = [] # from control[fullcode, ...]
#dict = {} # key: trtid10, value: [[numerator, denominator], [numerator, denominator], ...]
conn = psycopg2.connect("host='localhost' dbname='LTDB' user='neighborhood' password='Tomas159'")
curs = conn.cursor()
curs.execute("SELECT * From result LIMIT 0")
columnsOfResult = [desc[0] for desc in curs.description]
#print(columnsOfResult)
# set column list for query from control['codes'] in the result columns
colList = ''
for fullcode in control['codes']:
# separate group and code (e.g. '1 nhwhtXX' 1 is group number and nhwhtXX is code )
prefix = fullcode.split()[0]; # '1-01'
codeyear = fullcode.split()[1]; # 'nhwhtYY'
if codeyear in columnsOfResult:
colList += codeyear + ', '
#codes.append([fullcode, numerator, denominator, formula, shortname])
codes.append(prefix + ' ' + codeyear) # '1-01 nhwhtYY'
if confMsg:
self.logwrite("Configuration file is invalid. " + confMsg,gui.LOG_ERR)
return
# determine if postgresql is running
if cmdline.runningprocess('postgres'):
self.logwrite('PostgreSQL is running',gui.LOG_NOTE)
self._bSQL = True
# update state
self._setstate(_STATE_STORE_)
curs = None
try:
# attempt to connect and set state accordingly
self._conn = psql.connect(host=self._conf['store']['host'],
dbname=self._conf['store']['db'],
user=self._conf['store']['user'],
password=self._conf['store']['pwd'])
# set to use UTC and enable CONN flag
curs = self._conn.cursor()
curs.execute("set time zone 'UTC';")
self._conn.commit()
self._setstate(_STATE_CONN_)
self.logwrite("Connected to database",gui.LOG_NOTE)
except psql.OperationalError as e:
if e.__str__().find('connect') > 0:
self.logwrite("PostgreSQL is not running",gui.LOG_WARN)
self._setstate(_STATE_STORE_,False)
elif e.__str__().find('authentication') > 0:
self.logwrite("Authentication string is invalid",gui.LOG_ERR)
sys.exit(-1)
# set up AMQP
if not args.loadpickles:
connection = pika.BlockingConnection(parameters=parameters)
channel = connection.channel()
channel.exchange_declare(amqp_exchange, type="fanout")
channel.queue_declare(queue=amqp_queue)
channel.queue_bind(exchange=amqp_exchange, queue=amqp_queue)
# set up DB connection
if not dry_run:
connect_string = "port='" + str(db_port) + "' dbname='" + db_name + "' user='" + db_user + "' host='" + db_host + "' password='" + db_password + "'"
conn = psycopg2.connect(connect_string)
cursor = conn.cursor()
query_counter = 0
def db_query_execute(query, parms):
global query_counter
if dry_run:
if parms is not None:
print(query % parms)
logging.info(query % parms)
else:
print(query)
else:
try:
if parms is not None:
dbname = input("Enter the DB name: ")
dbuser = input("Enter the DB user: ")
dbpass = getpass.getpass("Enter the password for " + dbuser + ": ")
dbhost = input("Enter the host[localhost]: ") or "localhost"
usertoupdate = input("Enter the user you will change the password: ")
newpass = getpass.getpass("Enter the new password for "+usertoupdate+": ")
newpass_crypt = CryptContext(['pbkdf2_sha512']).encrypt(newpass)
"""
try to connect with the DB and make the update with the new password.
if the connection failed return a message.
"""
try:
conn = psycopg2.connect("dbname='" + dbname + "' user='" + dbuser + "\
' host='" + dbhost + "\
' password='" + dbpass + "'")
print("Opened database successfully")
cur = conn.cursor()
cur.execute("UPDATE res_users SET password_crypt = '"+newpass_crypt+"\
' WHERE login = '"+usertoupdate+"'")
conn.commit()
conn.close()
print("Password for "+usertoupdate+" has been updated successfully")
except:
print("Unable to connect to the database")
# input and process
poly = None
if options.bbox:
b = options.bbox
poly = box(b[0], b[1], b[2], b[3])
if options.poly:
tpoly = poly_parse(options.poly)
poly = tpoly if not poly else poly.intersection(tpoly)
if HAS_PSYCOPG and (options.area or options.cities):
passwd = None
if options.password:
passwd = getpass.getpass("Please enter your password: ")
try:
db = psycopg2.connect(database=options.dbname, user=options.user,
password=passwd, host=options.host, port=options.port)
if options.area:
tpoly = read_db(db, options.area)
poly = tpoly if not poly else poly.intersection(tpoly)
if options.cities:
tpoly = read_cities(db, options.cities)
poly = tpoly if not poly else poly.intersection(tpoly)
db.close()
except Exception as e:
logging.error("Error connecting to database: %s", e.pgerror or e)
sys.exit(3)
if options.list:
generator = ListGenerator(options.list, metatile=options.meta)
elif poly:
generator = PolyGenerator(poly, list(range(options.zooms[0], options.zooms[1] + 1)),
conn_kwargs = {
"database": database,
"host": host,
"user": user,
"password": kwargs.get("password"),
"port": port,
"connect_timeout": kwargs.get("connect_timeout", 15),
"gssencode": kwargs.get("gssencmode", "disable"),
}
allow_failover = kwargs.pop("allow_failover", True)
conn_kwargs.update(kwargs)
attempt = 0
while attempt < 3:
attempt += 1
try:
return psycopg2.connect(**conn_kwargs)
except psycopg2.ProgrammingError as exp:
# Likely gssencode is not permitted
if "gssencode" in conn_kwargs:
conn_kwargs.pop("gssencode")
else:
warnings.warn(
f"database connection failure: {exp}", stacklevel=2
)
if attempt == 3:
raise exp
except psycopg2.OperationalError as exp:
# as a stop-gap, lets try connecting to iemdb2
host2 = "iemdb2.local" if allow_failover else host
conn_kwargs["host"] = host2
if attempt == 3:
raise exp
def connect(self, database,user,password,host,port=5432):
try:
self.connection = psycopg2.connect(database=database, user=user, password=password, host=host, port=port)
self._cursor = self.connection.cursor(cursor_factory=psycopg2.extras.DictCursor)
except psycopg2.OperationalError as err:
print "Problem connecting to database - ", err
raise Exception("PostgreSql - problem connecting to %s" %database)
def bulkinsert_SF0(url: str, table_name: str = 'quandl_sf0'):
con = psycopg2.connect(url)
con.autocommit = True
cur = con.cursor()
cur.execute("DROP TABLE IF EXISTS {0};".format(table_name))
cur.execute(create_sf.format(table_name))
data = bulkdownload_sf0()
con = psycopg2.connect(url)
con.autocommit = True
insert_df(con, table_name, data)
cur.execute(create_sf_indices.format(table_name))
def __export_sections(self):
if not QgsProject.instance().readEntry("albion", "conn_info", "")[0] \
or not self.__current_graph.currentText():
return
fil = QFileDialog.getSaveFileName(None,
u"Export section",
QgsProject.instance().readEntry("albion", "last_dir", "")[0],
"Section files (*.obj *.txt)")
if not fil:
return
QgsProject.instance().writeEntry("albion", "last_dir", os.path.dirname(fil)),
conn_info = QgsProject.instance().readEntry("albion", "conn_info", "")[0]
con = psycopg2.connect(conn_info)
cur = con.cursor()
if fil[-4:] == '.txt':
cur.execute("select albion.export_polygons('{}')".format(self.__current_graph.currentText()))
open(fil, 'w').write(cur.fetchone()[0])
elif fil[-4:] == '.obj':
cur.execute("""
select albion.to_obj(st_collectionhomogenize(st_collect(albion.triangulate_edge(ceil_, wall_))))
from albion.edge
where graph_id='{}'
""".format(self.__current_graph.currentText()))
open(fil, 'w').write(cur.fetchone()[0])
con.close()