You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python OOP操作MySQL遇TypeError:'str'对象不可调用问题求助

解决TypeError: 'str' object is not callable及代码其他问题

核心错误原因

crearTabla方法中错误地将SQL语句赋值给self.miCursor.execute(使用了=),覆盖了原本的execute方法,导致后续调用execute时实际是调用一个字符串,触发TypeError: 'str' object is not callable。

其他代码问题及修复点

  • 表结构字段类型不匹配:stock字段定义为INT,但DEFAULT值是字符串'SIN STOCK',类型冲突。需将stock改为VARCHAR类型,或把默认值设为数字(如0)。
  • INSERT语句语法错误:字符串类型的nombre字段未加引号,直接拼接会导致SQL语法错误,同时存在SQL注入风险,应使用参数化查询替代字符串拼接。
  • UPDATE语句冗余关键字:UPDATE TABLE productos多了TABLE关键字,正确语法为UPDATE productos。
  • SELECT操作无需commit:只有写操作(INSERT/UPDATE/DELETE)需要commit,SELECT操作不需要执行该步骤。

修复后的完整代码

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):
        # 修复:去掉=,改为调用execute方法
        self.miCursor.execute('''
            CREATE TABLE productos (
                id INT PRIMARY KEY AUTO_INCREMENT,
                nombre VARCHAR(20) UNIQUE NOT NULL,
                precio INT NOT NULL,
                stock VARCHAR(20) DEFAULT 'SIN STOCK'
            )
        ''')
        print('\n ¡Tabla creada con éxito!')

    def insertarProductos(self, nombre, precio, stock):
        # 修复:使用参数化查询,避免SQL注入和语法错误
        sql_query = "INSERT INTO productos (nombre, precio, stock) VALUES (%s, %s, %s)"
        self.miCursor.execute(sql_query, (nombre, precio, stock))
        self.conexion.commit()
        print('\n ¡Producto agregado con éxito!')
    
    def seleccionProductos(self, id):
        # 修复:使用参数化查询,去掉不必要的commit
        sql_query = 'SELECT * FROM productos WHERE id = %s'
        self.miCursor.execute(sql_query, (id,))
        self.peticion = self.miCursor.fetchall()
        for i in self.peticion:
            print('Nombre:', i[1], 'Precio:', i[2], 'Stock:', i[3])
    
    def eliminarProductos(self, id):
        # 修复:使用参数化查询
        sql_query = 'DELETE FROM productos WHERE id = %s'
        self.miCursor.execute(sql_query, (id,))
        self.conexion.commit()
        print('\n ¡Producto eliminado con éxito!')
    
    def actualizarProductos(self, id, precio):
        # 修复:去掉冗余的TABLE关键字,使用参数化查询
        sql_query = 'UPDATE productos SET precio = %s WHERE id = %s'
        self.miCursor.execute(sql_query, (precio, 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()

内容的提问来源于stack exchange,提问作者Naujel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 15:30:41