Passing a variable as a list of arguments - python

My code is below. I'm just getting the basic functionality working before making more of the database, but I've run into a problem - Is there any way to pass a variable into four different arguments? My create_person function uses four arguments, but I need to initiate this after I create a Person object.
import os
import sqlite3
from personClass import *
#Connection to database - ToDoDB.db
conn = sqlite3.connect('ToDoDB.db')
cursor = conn.cursor()
def create_table_ToDo():
cursor.execute("""CREATE TABLE ToDo (
Forename text,
Surname text,
FirstChore text,
SecondChore text
)""")
print("ToDo table successfuly created!")
conn.commit()
def create_person(Forename, Surname, FirstChore, SecondChore):
query= "INSERT INTO ToDo (Forename, Surname, FirstChore, SecondChore)values (?,?,?,?);" #Inserts values below into this - question mark to sanitize first -
cursor.execute(query,(Forename, Surname, FirstChore, SecondChore)) #- then executes this command
conn.commit() #Commit and close after each function to save
print("New person and tasks added to the list of users")
#create_table_ToDo()
johnTest = Person("John", "Test", "Ironing clothes", "Washing dishes")
print(johnTest)
create_person(johnTest)
I've included my person class here just in case it helps.
class Person(ToDo):
def __init__(self, firstName, lastName, choreOne, choreTwo):
super().__init__(choreOne, choreTwo)
self.firstName = firstName
self.lastName = lastName
def getName(self):
print("My name is " + self.firstName + " " + self.lastName)
def getTasks(self):
print("My name's " + self.firstName + " and my tasks are " + self.choreOne + ", " + self.choreTwo)
def __repr__(self):
response = "{},{},{},{}".format(
self.firstName,
self.lastName,
self.choreOne,
self.choreTwo)
return response

You can use python's built-in getattr method to access the attribute values of an object. The following line should work:
create_person(getattr(johnTest, 'firstName'), getattr(johnTest, 'lastName'), getattr(johnTest, 'choreOne'), getattr(johnTest, 'choreTwo'))

Related

I am creating a backend for a habit tracker using OOP but I get a "NameError: name not defined when calling the create method"

This backend for habit tracking app gives a NameError "name does not exist". The values are passed to the class but when create is called, it throws a NameError.
class habit(object):
def __init__(self, name, period):
self.name = name
self.period = period
#self.hab_oper = hab_oper
def create(self):
self.name = name
self.period = period
#self.hab_oper = hab_oper
day = ftime(period)
db = sqlite3.connect("../habit/habit.db")
cur = db.cursor()
#query to incert input name to create habit in database of selected pereiod
cur.execute(f"INSERT INTO {period} ('name', 'first') VALUES ('{name}',{day})")
db.commit() #makes changes to database permanent
cur.close() #closes connection to database
db.close()
print(f" Habit name is {name} in {period}")
cre_hab = habit("reading", "daily")
cre_hab.create()
These two lines in create:
self.name = name
self.period = period
Are backwards: you meant:
name =self.name
period = self.period

How to find last inserted bookId from table in sqllite database using Python code?

import sqlite3
from sqlite3 import Error
class database_tasks:
bookId = 0
studentId = 0
def create_connection(self):
try:
conn = sqlite3.connect('library Management.db')
return conn
except Error as e:
print(e)
def insert(self, conn,dbname, name, writer='none'):
c = conn.cursor()
if dbname == "Book_database":
database_tasks.bookId += 1
#sql= "INSERT INTO Book_database VALUES(" + database_tasks.bookId + "," + name + "," + writer + ")"
c.execute ("INSERT INTO Book_database VALUES(?,?,?)",(database_tasks.bookId, name, writer))
The bookId always set to 1 whenever new record is inserted. But I want to insert record with bookId 1 greater than the last inserted record.
How do I initialize this bookId class variable to one more than the last inserted record?
import sqlite3
from sqlite3 import Error
class database_tasks:
def __init__(self,bookId=0,studentId=0):
self.bookId=bookId
self.studentId=studentId
def create_connection(self):
try:
conn = sqlite3.connect('library Management.db')
return conn
except Error as e:
print(e)
def insert(self, conn,dbname, name, writer='none'):
c = conn.cursor()
if dbname == "Book_database":
self.bookId += 1
#sql= "INSERT INTO Book_database VALUES(" + database_tasks.bookId + "," + name + "," + writer + ")"
c.execute ("INSERT INTO Book_database VALUES(?,?,?)",(database_tasks.bookId, name, writer))
you can initialize class as:
data = database_tasks()
or
data = database_tasks(bookId=<id>,studentId=<id>)
and insert records:
data.insert(coon,dbname,name,writer)
let me know if this help.
I'm not sure I understand your question. You are already declaring bookId as a class variable/ static variable. Getters and setters don't work in python like they do in languages like java. But for a class variable, you wouldn't need a getter and setter method. If you would like to change a class variable, you can access it outside of the class with a call to database_tasks.bookId.

name error first_name is not defined, after I defined it

I'm trying to make a function that returns a fully formmated full name, here is the code,
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted."""
full_name = (first_name + ' ' + last_name)
return full_name.title()
_musician = get_formatted_name('jimi', 'hendrix')
print(musician)
get_formatted_name(first_name, last_name)
I keep getting an error in the shell, NameError: name 'first_name' is not defined.
You haven't defined first_name anywhere. You have tried to use it without defining it anywhere first.
To get the code above to work you need to get rid of the last line, de-indent the final 2, rename _musician to musician and it will work, as below:
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted."""
full_name = (first_name + ' ' + last_name)
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)

Taking list of elements as param in Class method

I have a class Dbcrud() that I will outline below.
I want to take several parameters from a method: db_select() one being selected_fields which would be a list of fields.
Im having trouble forming my method db_select() to allow multiple fields to be defined for selected_fields.
Can someone help?
Thank you
UPDATED
class DbCrud:
query_stmt_list = ['SELECT','INSERT','UPDATE','DELETE','FROM','WHERE']
def __init__(self):
self.query_stmt_list = DbCrud.query_stmt_list
self.query_stmt_list = query_stmt_list
def set_db_settings(self, host, username, passwd, database):
self.host = host
self.username = username
self.passwd = passwd
self.database = database
db = pymysql.connect(host=host, user=username, passwd=passwd, db=database)
return db
def db_select(self, selected_fields, table, where_field):
self.selected_fields = selected_fields
self.table = table
self.where_field = where_field
try:
with db.cursor() as cursor:
sql_tld_id_query = self.query_stmt_list[0] + selected_fields* + self.query_stmt_list[4] + table + self.query_stmt_list[5] + where_field + '=' + %s
cursor.execute(sql_tld_id_query, (self.site_search_url,))
tld_id_value = cursor.fetchone()
except:
db.rollback()
pass
You have few issues here:
1.
You need that row at the init method (as this is the c'tor of the class)
Also as query_stmt_list is a static member, you should access him with the class name as prefix.
def __init__(self):
self.query_stmt_list = DbCrud.query_stmt_list
2.
You can't define a function param with selected_fields[], it's a syntax error, you can pass to selected_fields whatever you like.
def db_select(self, selected_fields, table, where_field):
3.
When you try to use the variable query_stmt_list (at the following line of code i've attached), do you mean you want the class member or the instance member?
If instance you should change it to self.query_stmt_list
If the class member, you should change it to DbCrud.query_stmt_list
sql_tld_id_query = query_stmt_list[0] + selected_fields* + query_stmt_list[4] + table + query_stmt_list[5] + where_field + '=' + %s
Also, in order to loop though the selected_fields you could do:
query_stmt_list[0] + ", ".join(item for item in self.selected_fields) + query_stmt_list[4] ...
You can always expect selected_fields to be a list so you can use ', '.join:
def db_select(self, selected_fields, table, where_field):
query = 'select {selected_fields} {table} where {where_field} = 1'
query = query.format(selected_fields=', '.join(selected_fields),
table=table, where_field=where_field)
.
.
obj.db_select(['col_a'], 'table_a', 'where_field_a')
Note that this is vulnerable to SQL injection, but so is your original code (if it wasn't for the syntax errors it currently has).

Jython Mule ArrayList Serializing

I am using the Python Component to return an array list of employee objects
I am getting the following error message. I am able to get back results from db and the issue seems to be in the employees array list serializing. Any help would be greatly appreciated.
Infinite recursion (StackOverflowError) (through reference chain: org.python.core.PyType["base"]->org.python.core.PyNone["type"]->
Infinite recursion (StackOverflowError) (through reference chain: org.python.core.PyType["base"]->org.python.core.PyNone["type"]->org.python.core.PyType["base"]->org.python.core.PyType["base"]->org.python.core.PyType["base"]->org.python.core.PyNone[...********************************************************************************
Root Exception stack trace:
java.lang.StackOverflowError
employees = ArrayList()
class Employee:
def __init__(self, empid, username):
self.empid = empid
self.username = username
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection("", "", "")
statement = connection.createStatement()
resultSet = statement.executeQuery("select * from xyz" + " where USER_EMPLOYEE_ID = '" + payload + "'");
while resultSet.next():
print "%s (%s)" % (resultSet.getString(1), resultSet.getString(2))
emp = Employee(resultSet.getString(1), resultSet.getString(2))
System.out.println(" Employee Details " + emp.empid)
employees.add(emp)
print type(employees)
result = employees

Categories

Resources