I'm starting to practice MySQL basics with Python OOP. I started with basic point of sale and I'm getting an error: TypeError: 'str' object is not callable, which I don't know how to solve. It's in spanish but I think it's understandable.
This is my program:
import pymysql as sql
class Database:
def __init__(self):
self.conexion = sql.connect(
host = 'localhost',
user = 'root',
password = '',
db = 'PythonBD'
)
print('\n ¡Conexión con base de datos establecida con éxito!\n')
self.miCursor = self.conexion.cursor()
def crearTabla(self):
self.miCursor.execute = ('''
CREATE TABLE productos (
id INT PRIMARY KEY AUTO_INCREMENT,
nombre VARCHAR(20) UNIQUE NOT NULL,
precio INT NOT NULL,
stock INT DEFAULT 'SIN STOCK'
)
''')
print('\n ¡Tabla creada con éxito!')
def insertarProductos(self, nombre, precio, stock):
self.miCursor.execute(f"INSERT INTO productos VALUES({nombre}, {precio}, {stock})")
self.conexion.commit()
print('\n ¡Productos agregados con éxito!')
def seleccionProductos(self, id):
self.miCursor.execute(f'SELECT * FROM productos WHERE id = {id}')
self.peticion = self.miCursor.fetchall()
for i in self.peticion:
print('Nombre:', i[1], 'Precio:', i[2], 'Stock:', i[3])
self.conexion.commit()
def eliminarProductos(self, id):
self.miCursor.execute(f'DELETE FROM productos WHERE id = {id}')
self.conexion.commit()
print('\n ¡Producto eliminado con éxito!')
def actualizarProductos(self, id, precio):
self.miCursor.execute(f'UPDATE TABLE productos SET precio = {precio} WHERE id = {id}')
self.conexion.commit()
print('\n ¡Producto actualizado con éxito!')
def borrarTabla(self):
self.miCursor.execute('DROP TABLE productos')
self.conexion.commit()
print('\n ¡Tabla borrada con éxito!')
def cerrarConexion(self):
self.conexion.close()
database = Database()
#database.borrarTabla()
database.crearTabla()
database.insertarProductos('Manzana', 990, 5)
database.insertarProductos('Plátano', 990, 10)
database.cerrarConexion()
CodePudding user response:
Your traceback trace complained about this line:
self.miCursor.execute(f"INSERT INTO productos VALUES('{nombre}', {precio}, {stock})")
TypeError: 'str' object is not callable
Which would indicate that self.miCursor.execute
is a str
type and you're trying to call it as a method.
So if you look at the rest of the code, you have a bug in your crearTable
method:
def crearTabla(self):
self.miCursor.execute = ('''
CREATE TABLE productos (
id INT PRIMARY KEY AUTO_INCREMENT,
nombre VARCHAR(20) UNIQUE NOT NULL,
precio INT NOT NULL,
stock INT DEFAULT 'SIN STOCK'
)
''')
You assigned self.miCursor.execute
to be a str
with that CREATE TABLE
statement. Remove the assignment and your code should work:
def crearTabla(self):
self.miCursor.execute('''
CREATE TABLE productos (
id INT PRIMARY KEY AUTO_INCREMENT,
nombre VARCHAR(20) UNIQUE NOT NULL,
precio INT NOT NULL,
stock INT DEFAULT 'SIN STOCK'
)
''')