Search code examples
pythonsqlcursor

Using Python Cursor class to execute multimatch query with LIKE statement


Attempting to execute a select query matching 4 variables, one of which is checking for a string in the title. How do I execute a LIKE statement with the python cursor class? or another way?

stmt = "SELECT * FROM publication NATURAL JOIN journal NATURAL JOIN authors WHERE name = ? AND year = ? AND booktitle = ? AND title LIKE '%%%s%%'" % (input_names, input_year, input_booktitle, input_string) 
print(stmt)
cur.execute(stmt)

Edit: table schemas

%%sql
DROP TABLE IF EXISTS publication;
CREATE TABLE publication(
    ID INT PRIMARY KEY NOT NULL,
    title VARCHAR NOT NULL
);

/* Author Entity set and writes_for relationship */
DROP TABLE IF EXISTS authors;
CREATE TABLE authors(
    name VARCHAR(200) PRIMARY KEY NOT NULL,
    ID INT,
    title VARCHAR(200),
    FOREIGN KEY(id, title) REFERENCES publication(ID, title)
);

/* Journal Entity set and apart_of relationship */
DROP TABLE IF EXISTS journal;
CREATE TABLE journal(
    booktitle VARCHAR(200) PRIMARY KEY NOT NULL,
    pages INT,
    year INT(4),
    ID INT,
    title VARCHAR(200),
    FOREIGN KEY(ID, title) REFERENCES publication(ID, title)
);

Solution

  • I am thinking that the real problem is that you are doing join and you don't tell it from where to take the columns from(from which table).

    can you please try to add the tables? I am not sure it will help but lets try(because maybe you don't have the same columns name in these tables)

    like that?

    stmt = "SELECT * FROM publication NATURAL JOIN journal NATURAL JOIN
    authors WHERE authors.name = ? AND journal.year = ? AND
    journal.booktitle = ? AND journal.title LIKE     
    '%%%s%%'" % (input_names, input_year, input_booktitle, input_string) 
    print(stmt)
    cur.execute(stmt)
    

    second thing: you should use '%s' and not '?'

    stmt = "SELECT * FROM publication NATURAL JOIN journal NATURAL JOIN
    authors WHERE authors.name = '%s' AND journal.year = '%s' AND
    journal.booktitle = '%s' AND journal.title LIKE     
    '%%%s%%'" % (input_names, input_year, input_booktitle, input_string) 
    print(stmt)
    cur.execute(stmt)