1

I created a database using DB Browser for SQLite. Now I am trying to run queries to retrieve data from the database, and I have run into an issue. When I run the query in DB Browser, the query runs smoothly. When I attempt to run the same query in Java, I get an error message. I triple-checked the query string. I looked to make sure I was not using SQLite keywords incorrectly. Why am I getting an error when I run this query Java?

SELECT
    subject.id, main.name, main.link, subject.name, main_subject.weight
FROM 
    main_subject
LEFT JOIN 
    main ON main_subject.mainId = main.id
LEFT JOIN 
    subject ON main_subject.subjectId = subject.id

The query running correctly in DB Browser. enter image description here

MCVE:

Main

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author sedrick
 */
public class Main
{

    public static void main(String[] args)
    {
        try (DatabaseHandler databaseHandler = new DatabaseHandler()) {
            List<BySubjectItemTwo> bySubjectItemTwos = databaseHandler.getBySubjectItems();
            bySubjectItemTwos.forEach(System.out::println);
            //databaseHandler.getByTitleItems().forEach(System.out::println);
        }
        catch (Exception ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

DatabaseHandler

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author sedrick
 */
public class DatabaseHandler implements AutoCloseable
{

    String dbString = "jdbc:sqlite:qDatabase.sqlite3";
    private Connection conn;

    public DatabaseHandler()
    {
        try {
            conn = DriverManager.getConnection(dbString);
            System.out.println("Connected to qDatabase!");
        }
        catch (SQLException ex) {
            Logger.getLogger(DatabaseHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void close() throws Exception
    {
        conn.close();
    }

    public List<BySubjectItemTwo> getBySubjectItems()
    {
        List<BySubjectItemTwo> returnList = new ArrayList();

        String sqlString = "SELECT subject.id, main.name, main.link, subject.name, main_subject.weight FROM main_subject LEFT JOIN main ON main_subject.mainId = main.id LEFT JOIN subject ON main_subject.subjectId = subject.id";
        try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sqlString)) {
            while (rs.next()) {
                System.out.println(rs.getInt("subject.id") + " - " + rs.getString("main.name") + " - " + rs.getString("main.link") + " - " + rs.getString("subject.name") + " - " + rs.getInt("main_subject.weight"));
                //returnList.add(new BySubjectItemTwo(rs.getInt("subject.id"), rs.getString("main.name"), rs.getString("main.link"), rs.getString("subject.name"), rs.getInt("main_subject.weight")));
            }
        }
        catch (SQLException e) {
            System.out.println(e.getMessage());
        }

        return returnList;
    }  
}

BySubjectItemTwo

/**
 *
 * @author sedrick
 */
public class BySubjectItemTwo
{

    private int subjectId;
    private String mainName;
    private String mainLink;
    private String subjectName;
    private int mainSubjectWeight;

    public BySubjectItemTwo(int subjectId, String mainName, String mainLink, String subjectName, int mainSubjectWeight)
    {
        this.subjectId = subjectId;
        this.mainName = mainName;
        this.mainLink = mainLink;
        this.subjectName = subjectName;
        this.mainSubjectWeight = mainSubjectWeight;
    }

    public int getSubjectWeight()
    {
        return mainSubjectWeight;
    }

    public void setSubjectWeight(int mainSubjectWeight)
    {
        this.mainSubjectWeight = mainSubjectWeight;
    }

    public int getSubjectId()
    {
        return subjectId;
    }

    public void setSubjectId(int subjectId)
    {
        this.subjectId = subjectId;
    }

    public String getMainName()
    {
        return mainName;
    }

    public void setMainName(String mainName)
    {
        this.mainName = mainName;
    }

    public String getMainLink()
    {
        return mainLink;
    }

    public void setMainLink(String mainLink)
    {
        this.mainLink = mainLink;
    }

    public String getSubjectName()
    {
        return subjectName;
    }

    public void setSubjectName(String subjectName)
    {
        this.subjectName = subjectName;
    }

    @Override
    public String toString()
    {
        StringBuilder sb = new StringBuilder();
        sb.append("BySubjectItemTwo{subjectId=").append(subjectId);
        sb.append(", mainName=").append(mainName);
        sb.append(", mainLink=").append(mainLink);
        sb.append(", subjectName=").append(subjectName);
        sb.append(", subjectWeight=").append(mainSubjectWeight);
        sb.append('}');
        return sb.toString();
    }
}

Error

----------< sed.work:CreateDatabaseByTitleAndSubjectDatabase >----------
Building CreateDatabaseByTitleAndSubjectDatabase 1.0-SNAPSHOT
--------------------------------[ jar ]---------------------------------

--- exec-maven-plugin:1.5.0:exec (default-cli) @ CreateDatabaseByTitleAndSubjectDatabase ---
Connected to qDatabase!
[SQLITE_ERROR] SQL error or missing database (ambiguous column name: subject.id)
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time:  1.484 s
Finished at: 2020-10-16T12:42:35-05:00
------------------------------------------------------------------------

Netbean's Info

Product Version: Apache NetBeans IDE 12.1
Java: 15; Java HotSpot(TM) 64-Bit Server VM 15+36-1562
Runtime: Java(TM) SE Runtime Environment 15+36-1562
System: Windows 10 version 10.0 running on amd64; Cp1252; en_US (nb)
Maven Project

1 Answer 1

1

This:

FROM main_subject, main, subject

is the problem with your query.

Remove , main, subject from your statement.
The tables main and subject are correctly joined after the LEFT joins.
When you use them also in the FROM clause this creates additional references and CROSS joins to the same tables.

Also, although SQLite allows a query to return more than 1 columns with the same name, it is a good practice to alias columns so that in the resultset all column names are different.
So give aliases to main.name and subject.name, something like this:

SELECT subject.id, main.name AS main_name, ..., subject.name AS subject_name, ...

and when you retrieve the column values don't use the table prefixes:

System.out.println(rs.getInt("id") + " - " + rs.getString("main_name") + " - " + rs.getString("link") + " - " + rs.getString("subject_name") + " - " + rs.getInt("weight"));
Sign up to request clarification or add additional context in comments.

6 Comments

Hello @forpas. Sorry, I updated the String. I was trying different stuff out and came up with that incorrect String.
@Sedrick if you run the query as it was before you edited with: FROM main_subject, main, subject in DB Browser for SQLite you will get the error: ambiguous column name: subject.id just like the error message you get. So the actual code that produces this error is not the code that you have currently in your question.
Hello forpas, I copied and pasted directly from DB Browser. I also typed the String directly. I also cleaned and build my project.
@Sedrick As I said this query does not throw this error but the previous does.
Hello forpas, String sqlString = "SELECT subject.id, main.name, main.link, subject.name, main_subject.weight FROM main_subject LEFT JOIN main ON main_subject.mainId = main.id LEFT JOIN subject ON main_subject.subjectId = subject.id"; is the String I am currently using. It's giving me the error.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.