0

I do this from MyPhpAdmin it works perfectly. I want all columns it also works perfectly. But I just want the value inside one column, it does not work and I would like to know why. The result I get is a: tuple('year',) and I expect a date like (20200612). BTW: I don't know if this is useful but just in case, these methods are in different files. I just put them together so you can see. BTW2: If you think of better names or some mistakes feel free to correct me. I'm translating my project into English. Code:

def __set_year_to_student_subject(self,legajo:str,cod:str) -> None:
        con,dao = self.__set_conecction_with_data_base()
        year = dao.obtain_field_from_student_subject(legajo,cod,"year")
        self.__subject.set_year_by_argument(year)
        con.close()

def obtain_field_from_student_subject(self,legajo:str,code:str,field:str) -> tuple:
        try:
            cursor = self.__conecction.getcursor()
            cursor.execute(f"SELECT '{field}' FROM {NAME_TABLE_SUB_ALU} WHERE idLegajo = \                         
                           '{legajo}' AND idcode = '{code}'")
            data = cursor.fetchone()
            cursor.close()
        except Error as e:
            raise ValueError(f"\n{strC('Error in mysql: Issue when trying to obtain data from 
                                 a field.',9)}\n{e}\n")
       return data
  • 1
    Don't put the column name in single quotes. – Barmar Jun 23 '22 at 20:50
  • And don't substitute values directly into the SQL, use placeholders and parameters. – Barmar Jun 23 '22 at 20:52
  • @Barmar Thanks, now works. But I don't understand your last message. Do you say that is bad to pass the field as a parameter? – Facundo Borrás Jun 23 '22 at 21:06
  • 1
    You can use string formatting for column and table names because you can't use placeholders for them. But you should use placeholders for `legajo` and `code`. – Barmar Jun 23 '22 at 21:33
  • See https://stackoverflow.com/questions/902408/how-to-use-variables-in-sql-statement-in-python – Barmar Jun 23 '22 at 21:34
  • So you are saying that I should do the following: Send as a parameter the name of the columns (e.g., legajo and code). So, I don't write legajo and code and I write %s and %s and then after the string I write,(name_column1,name_column2). Is that correct? – Facundo Borrás Jun 23 '22 at 21:40
  • 1
    Yes, that's correct. That's unrelated to the problem you had, it's just general good practice. – Barmar Jun 23 '22 at 21:43
  • Yes: I didn't know that. I will implement it. – Facundo Borrás Jun 23 '22 at 21:52

0 Answers0