Reputation: 133
This is my database manager class:
class DatabaseManager(object):
def __init__(self):
super().__init__()
self.conn = sqlite3.connect('artist.db')
self.c = self.conn.cursor()
def create_table(self):
self.c.execute(
'CREATE TABLE IF NOT EXISTS artists(title TEXT, artist TEXT, album TEXT, year INTEGER, '
'genre TEXT, ext TEXT, path TEXT, art TEXT )')
self.c.close()
self.conn.close()
def insert(self, song):
self.c.execute(
'INSERT INTO artists(title, artist, album, year, genre, ext, path, art) VALUES(?, ?, ?, ?, ?, ?, ?, ?)',
(song.title, song.artist, song.album, song.year, song.genre, song.ext, song.path, song.art))
self.conn.commit()
self.c.close()
self.conn.close()
def retrieve_all(self):
self.c.execute('SELECT * FROM artists')
data = self.c.fetchall()
self.c.close()
self.conn.close()
return data
There are more methods but this is not important. When i start the app i call create_table()
and when i need some database action i create another obect(or remake the past one) to call insert
for example.
db = DatabaseManager()
print(db.retrieve_artist('asdf'))
db = DatabaseManager()
print(db.retrieve_all())
Is there any way to avoid this? In Java there is anonymous calls:
new DatabaseManager().retrieve_artist("asdf")
Is anything similar possible in Python?
Upvotes: 0
Views: 143
Reputation:
As @Remcogerlich said, you are assigning the instantiation to a variable. If you just don't do so, you can approach what you want.
DatabaseManager().retrieve_artist('asdf')
AnyOtherClass().callAnyMethod()
# both disappeared
In this way, Python executes the instantiation, calls the method you want to, and since you don't tell it to assign to any variable, it "disappears".
You may even do that with class functions, like this:
ClassWithClassMethods.callAnyClassMethod()
However, I wouldn't recommend you to work with that on that way. Normally, database connections are established as an instantiation, used as long as you need to, and when you don't need them anymore you close them safely. I think you are not doing that there, and are wasting memory usage, I guess (anyone correct me if I'm wrong). It's easier that you create an object for each time you want to use the database for long, and once you finish in that piece of code, you close the connection and remove the object.
Upvotes: 1