Python3 - Database sqlite3 - sqlite3.OperationalError: no such column: - python-3.x

I am trying to create a small and simple accountancy program, here is my code:
import sqlite3 as lite #db
import sys #db
from pathlib import Path #check file exists
successful_login = False
def login_process():
print("Welcome to your accountance program, write your username: ")
user = input()
my_file = Path("./%s" % (user,))
if my_file.is_file():
con = lite.connect(user)
main_loop()
else:
con = lite.connect(user)
print("Write the name of your bank account: ")
bankaccount = input()
print("Write how much money do you have on it: ")
starting_money = int(input())
print(starting_money)
with con:
cur = con.cursor()
cur.execute("CREATE TABLE Bank(Name TEXT, Money INT)")
cur.execute("INSERT INTO Bank VALUES (%s,%s)" % (bankaccount,starting_money))
main_loop()
And here is the error:
Why is this happening ?
Thank you !

From the python sqlite API doc:
# Never do this -- insecure!
symbol = 'RHAT'
c.execute("SELECT * FROM stocks WHERE symbol = '%s'" % symbol)
(And examining this INSECURE example carefully should illuminate what is the error in this program).
Suggest you use the doc to learn how to use placeholders. It is an important habit to develop.

Related

How to do validation in python?

I am making a gui for employee management system using python tkinter and sqlite3.
In this gui user can add, view, delete amd update employee info.
def save():
con = None
try:
con = connect("pro.db")
cursor = con.cursor()
sql = "insert into Employee values('%d', '%s', '%f')"
id = int(aw_ent_id.get())
name = aw_ent_name.get()
lenstring = False
while not lenstring:
if len(name) >= 2:
lenstring = True
else:
showerror("error","Enter atleast 2 letters")
break
salary = float(aw_ent_salary.get())
cursor.execute(sql%(id, name, salary))
con.commit()
showinfo("success", "record added")
aw_ent_id.delete(0, END)
aw_ent_name.delete(0, END)
aw_ent_salary.delete(0, END)
aw_ent_id.focus()
except Exception as e:
con.rollback()
showerror("issue", e)
finally:
if con is not None:
con.close()
the code is running but i am getting some errors in validating name and salary.
for name i have done validating but its not working. I am getting an error
the data is getting saved even after getting error.
What should i do to make it right?
It is better to:
validate the inputs before saving to database
raise exception if len(name) is less than 2 instead of using while loop checking (actually the while loop is meaningless)
use placeholders to avoid SQL injection
Below is updated save():
# avoid using wildcard import
import tkinter as tk
from tkinter.messagebox import showinfo, showerror
import sqlite3
...
def save():
con = None
try:
# validate inputs
# use emp_id instead of id because id is built-in function
emp_id = int(aw_ent_id.get().strip()) # raise ValueError if not a valid integer
name = aw_ent_name.get().strip()
if len(name) < 2:
raise Exception('Name too short, at least 2 letters')
salary = float(aw_ent_salary.get().strip()) # raise ValueError if not a valid float number
# validations on inputs are passed, try saving to database
sql = 'insert into Employee values (?, ?, ?)' # use placeholders to avoid SQL injection
con = sqlite3.connect('pro.db')
cursor = con.cursor()
cursor.execute(sql, (emp_id, name, salary))
con.commit()
showinfo('Success', 'Employee added')
aw_ent_id.delete(0, tk.END)
aw_ent_name.delete(0, tk.END)
aw_ent_salary.delete(0, tk.END)
aw_ent_id.focus_set()
except Exception as e:
if con:
con.rollback()
showerror("Error", e)
finally:
if con:
con.close()
...

How to modify the PostgreSQL psycopg to accept variables instead of values

I am creating a dictionary attacking tool on PostgreSQL. The tool is inspired by the work of m8r0wn - enumdb tool. Mikes tool is aimed at MySQL and MSSQL. I aim to use the same approach he used but modify the actions and output file. The script should
1) Read a CSV file that contains targets and ports, one per line 127.0.0.1,3380.
2) when provided a list of usernames and/or passwords, it will cycle through each targeted host looking for valid credentials. By default, it will use newly discovered credentials to search for sensitive information in the host's databases via keyword searches on the table or column names.
3) This information can then be extracted and reported to a JSON, .csv or .xlsx output file.
I have a semi functional code, but I suspect the PostgreSQL connection function is not working due to the logic behind passing parameters. I am interested in suggestions on how best I could present the tools results as a JSON file.
I understand that in Python, we have several modules available to connect and work with PostgreSQL which include:
Psycopg2
pg8000
py-postgresql
PyGreSQL
ocpgdb
bpgsql
SQLAlchemy
see also https://www.a2hosting.co.za/kb/developer-corner/postgresql/connecting-to-postgresql-using-python
The connection methods I have tried include:
import psycopg2
from psycopg2 import Error
conn = psycopg2.connect(host=host, dbname=db_name, user=_user, password=_pass, port=port)
import pg
conn = pg.DB(host=args.hostname, user= _user, passwd= _pass)
sudo pip install pgdb
import pgdb
conn = pgdb.connect(host=args.hostname, user= _user, passwd= _pass)
I am not sure how to pass the different _user and _pass guesses into the pyscopg2 for instance, without breaking the code.
I have imported the following libraries
import re
import psycopg2
from psycopg2 import Error
import pgdb
#import MySQLdb
import pymssql
import argparse
from time import sleep
from sys import exit, argv
from getpass import getpass
from os import path, remove
from openpyxl import Workbook
from threading import Thread, activeCount
The PgSQL block is as follows:
##########################################
# PgSQL DB Class
##########################################
class pgsql():
def connect(self, host, port, user, passwd, verbose):
try:
con = pgdb.connect(host=host, port=port, user=user, password=passwd, connect_timeout=3)
con.query_timeout = 15
print_success("[*] Connection established {}:{}#{}".format(user,passwd,host))
return con
except Exception as e:
if verbose:
print_failure("[!] Login failed {}:{}#{}\t({})".format(user,passwd,host,e))
else:
print_failure("[!] Login failed {}:{}#{}".format(user, passwd, host))
return False
def db_query(self, con, cmd):
try:
cur = con.cursor()
cur.execute(cmd)
data = cur.fetchall()
cur.close()
except:
data = ''
return data
def get_databases(self, con):
databases = []
for x in self.db_query(con, 'SHOW DATABASES;'):
databases.append(x[0])
return databases
def get_tables(self, con, database):
tables = []
self.db_query(con, "USE {}".format(database))
for x in self.db_query(con, 'SHOW TABLES;'):
tables.append(x[0])
return tables
def get_columns(self, con, database, table):
# database var not used but kept to support mssql
columns = []
for x in self.db_query(con, 'SHOW COLUMNS FROM {}'.format(table)):
columns.append(x[0])
return columns
def get_data(self, con, database, table):
# database var not used but kept to support mssql
return self.db_query(con, 'SELECT * FROM {} LIMIT {}'.format(table, SELECT_LIMIT))
The MSSQL is as follows:
# MSSQL DB Class
class mssql():
def connect(self, host, port, user, passwd, verbose):
try:
con = pymssql.connect(server=host, port=port, user=user, password=passwd, login_timeout=3, timeout=15)
print_success("[*] Connection established {}:{}#{}".format(user,passwd,host))
return con
except Exception as e:
if verbose:
print_failure("[!] Login failed {}:{}#{}\t({})".format(user,passwd,host,e))
else:
print_failure("[!] Login failed {}:{}#{}".format(user, passwd, host))
return False
def db_query(self, con, cmd):
try:
cur = con.cursor()
cur.execute(cmd)
data = cur.fetchall()
cur.close()
except:
data = ''
return data
def get_databases(self, con):
databases = []
for x in self.db_query(con, 'SELECT NAME FROM sys.Databases;'):
databases.append(x[0])
return databases
def get_tables(self, con, database):
tables = []
for x in self.db_query(con, 'SELECT NAME FROM {}.sys.tables;'.format(database)):
tables.append(x[0])
return tables
def get_columns(self, con, database, table):
columns = []
for x in self.db_query(con, 'USE {};SELECT column_name FROM information_schema.columns WHERE table_name = \'{}\';'.format(database, table)):
columns.append(x[0])
return columns
def get_data(self, con, database, table):
return self.db_query(con, 'SELECT TOP({}) * FROM {}.dbo.{};'.format(SELECT_LIMIT, database, table))
The main function block:
def main(args):
try:
for t in args.target:
x = Thread(target=enum_db().db_main, args=(args, t,))
x.daemon = True
x.start()
# Do not exceed max threads
while activeCount() > args.max_threads:
sleep(0.001)
# Exit all threads before closing
while activeCount() > 1:
sleep(0.001)
except KeyboardInterrupt:
print("\n[!] Key Event Detected...\n\n")
exit(0)
if __name__ == '__main__':
version = '1.0.7'
try:
args = argparse.ArgumentParser(description=("""
{0} (v{1})
--------------------------------------------------
Brute force Juggernaut is a PgSQL brute forcing tool.**""").format(argv[0], version), formatter_class=argparse.RawTextHelpFormatter, usage=argparse.SUPPRESS)
user = args.add_mutually_exclusive_group(required=True)
user.add_argument('-u', dest='users', type=str, action='append', help='Single username')
user.add_argument('-U', dest='users', default=False, type=lambda x: file_exists(args, x), help='Users.txt file')
passwd = args.add_mutually_exclusive_group()
passwd.add_argument('-p', dest='passwords', action='append', default=[], help='Single password')
passwd.add_argument('-P', dest='passwords', default=False, type=lambda x: file_exists(args, x), help='Password.txt file')
args.add_argument('-threads', dest='max_threads', type=int, default=3, help='Max threads (Default: 3)')
args.add_argument('-port', dest='port', type=int, default=0, help='Specify non-standard port')
args.add_argument('-r', '-report', dest='report', type=str, default=False, help='Output Report: csv, xlsx (Default: None)')
args.add_argument('-t', dest='dbtype', type=str, required=True, help='Database types currently supported: mssql, pgsql')
args.add_argument('-c', '-columns', dest="column_search", action='store_true', help="Search for key words in column names (Default: table names)")
args.add_argument('-v', dest="verbose", action='store_true', help="Show failed login notices & keyword matches with Empty data sets")
args.add_argument('-brute', dest="brute", action='store_true', help='Brute force only, do not enumerate')
args.add_argument(dest='target', nargs='+', help='Target database server(s)')
args = args.parse_args()
# Put target input into an array
args.target = list_targets(args.target[0])
# Get Password if not provided
if not args.passwords:
args.passwords = [getpass("Enter password, or continue with null-value: ")]
# Define default port based on dbtype
if args.port == 0: args.port = default_port(args.dbtype)
# Launch Main
print("\nStarting enumdb v{}\n".format(version) + "-" * 25)
main(args)
except KeyboardInterrupt:
print("\n[!] Key Event Detected...\n\n")
exit(0)
I am aware that documentation states here http://initd.org/psycopg/docs/module.html states about how connection parameters can be specified. I would like to pass password guesses into the brute class and recursively try different combinations.
PEP-8 asks that you please give classes a name
starting with a capital letter, e.g. Pgsql.
You mentioned that the pgsql connect() method is not working properly,
but didn't offer any diagnostics such as a stack trace.
You seem to be working too hard, given that the sqlalchemy layer
has already addressed the DB porting issue quite nicely.
Just assemble a connect string starting with
the name of the appropriate DB package,
and let sqlalchemy take care of the rest.
All your methods accept con as an argument.
You really want to factor that out as the object attribute self.con.
The db_query() method apparently assumes that
arguments for WHERE clauses already appear, properly quoted, in cmd.
According to Little Bobby's mother,
it makes sense to accept query args according to the API,
rather than worrying about potential for SQL injection.

Python script placed in /usr/bin not saving data in sqlite db

I wrote a program which gets username and password from the user and creates a table in an SQLite DB then sends those data through a connection to DB.
It was working fine until I added the shebang in my code, then I made it executable(chmod +x) and after all, I put that file into /usr/bin so that I could use it anywhere in the terminal. now it runs but it doesn't work (it doesn't add data to DB).
here is my code:
#!/usr/bin/python3
__author__ = "Taha Jalili"
__license__ = "GPL"
__version__ = "1.0.0"
__email__ = "tahajalili#gmail.com"
import sys
import sqlite3
from sqlite3 import *
import inquirer
SQL_CREATE_STATEMENT = '''CREATE TABLE password
(id integer PRIMARY KEY NOT NULL,username text, password text, source text)'''
SQL_INSERT_STATEMENT = '''INSERT INTO password (username, password, source)VALUES(?,?,?)'''
DATABASE_PATH = '/home/taha/lessons/projects/passStorage/passDB.db'
def create_connection(db_file):
try:
conn = sqlite3.connect(db_file)
return conn
print('Connection created.')
except Error as e:
return e
# def create_table(connection, sql_commands):
# c = connection.cursor()
# c.execute(sql_commands)
# print('=> Table created.')
def get_input():
USERNAME = input('username: ')
PASSWORD = input('password: ')
SOURCE = input('source: ')
return USERNAME,PASSWORD,SOURCE
def insert_date(connection,data):
try:
c = connection.cursor()
c.execute(SQL_INSERT_STATEMENT, data)
print('=> Data insertion done.')
except Error as e:
return e
def show_info(connection):
c = connection.cursor()
info = c.execute('SELECT * FROM password ORDER BY id')
print('YOUR PASSWORDS'.center(45,'-'))
print('(id, username, password, source)')
for row in info:
print(row,'')
print('\n')
def ask_again():
user_choice = input("Wish to continue? Y/N ")
if user_choice == 'y' or user_choice == 'Y':
main()
elif user_choice == 'n' or user_choice == 'N':
print("==> BYE <==")
sys.exit(0)
def main():
conn = create_connection(DATABASE_PATH)
# create_table(conn, SQL_CREATE_STATEMENT)
questions = [
inquirer.List(
'job',
message = 'What should I do?',
choices=['Add data','Show saved data.']
),
]
answers = inquirer.prompt(questions)
if answers['job'] == 'Add data':
conn2 = create_connection(DATABASE_PATH)
insert_date(conn2,get_input())
elif answers['job'] == 'Show saved data.':
show_info(conn)
ask_again()
conn.commit()
conn.close()
if __name__ == '__main__':
main()

Why I am not able to connect to the database

import lot_details, car_details
import numpy as np
import sqlite3
conn = sqlite3.connect('parkingLot.db')
c = conn.cursor()
class Parking(object):
"""
Parking class which has details about parking slots
as well as operation performed on parking are present here
"""
def __init__(self):
self.slots = {}
def create_parking_lot(self, no_of_slots):
try:
c.execute('CREATE TABLE IF NOT EXISTS parkingTable(slot_no REAL, reg_no TEXT, colour TEXT, total_time TEXT,charge TEXT)')
except Exception as ex:
print("Couldn't make a table in DB")
no_of_slots = int(no_of_slots)
if len(self.slots) > 0:
print ("Parking Lot already created")
return
if no_of_slots > 0:
for i in range(1, no_of_slots+1):
temp_slot = lot_details.PSlot(slot_no=i, available=True)
self.slots[i] = temp_slot
print ("Created a parking lot with {} slots" .format(no_of_slots))
else:
print ("Number of slots provided is incorrect.")
return
Using above code I am trying to create a database(which is successful) but now I am not able to create the Table inside it using the above command.
I tried doing it separately its working there. But, I am not able to create it using above code.
Depending on how and where you are creating the Parking object I suspect this could be a scoping issue, either pass the db connection into the constructor or just create it in the constructor itself. Code modified for brevity. The following works for me.
import sqlite3
class Parking(object):
def __init__(self):
self.slots = {}
self.conn = sqlite3.connect('parkingLot.db')
def create_parking_lot(self, no_of_slots):
try:
cur = self.conn.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS parkingTable(slot_no REAL, reg_no TEXT, colour TEXT, total_time TEXT,charge TEXT)')
except Exception as ex:
print("Couldn't make a table in DB")
return
parking = Parking()
parking.create_parking_lot(5)

Python output is blank when i execute the following code:

This program is a banking system. It connects to an online database which contains customer details and transaction details. However, when I execute the code, I get a blank output in python 3.4.0 shell:
import pyodbc
cnxn = pyodbc.connect('Driver={SQL Server};'
'Server=***;'
'Database=***;'
'uid=***;pwd=***')
cursor = cnxn.cursor()
def MainMenu():
print('##############################\n\tWelcome to the XYZ Banking System\n##############################')
print()
print('PLEASE ENTER THE NUMBER CORRESPONDING TO YOUR DESIRED COMMAND IN THE PROMPT BELOW : \n\t1.ACCESS CUSTOMER DETAILS\n\t2.ACCESS TRANSACTION PORTAL\n##############################')
print()
var_UserInput=input('>>>')
if var_UserInput=='1':
return CustomerPortal()
def CustomerPortal():
cursor.tables()
rows = cursor.fetchall()
for row in rows:
print (row.customer)
MainMenu()
Try this. I've made a few changes:
Moved the connection string into the function
Modified the code to be closer to PEP-8 https://www.python.org/dev/peps/pep-0008/
Fixed indentation
Here's the code.
import pyodbc
def main_menu():
print('##############################\n\tWelcome to the XYZ Banking System\n##############################')
print()
print('PLEASE ENTER THE NUMBER CORRESPONDING TO YOUR DESIRED COMMAND IN THE PROMPT BELOW : \n\t1.ACCESS CUSTOMER DETAILS\n\t2.ACCESS TRANSACTION PORTAL\n##############################')
print()
var_user_input=input('>>>')
if var_user_input=='1':
return customer_portal()
def customer_portal():
cnxn = pyodbc.connect('Driver={SQL Server};'
'Server=***;'
'Database=***;'
'uid=***;pwd=***')
cursor = cnxn.cursor()
cursor.tables()
rows = cursor.fetchall()
for row in rows:
print (row.customer)
cursor.close()
if __name__ == "__main__":
main_menu()
Good luck!

Resources