java sqlite - display select - java

These are my tables:
http://sqlfiddle.com/#!5/acdb1
I want to display in Java something like raport:
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:project.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT stormtrooper.id, squad.id, platoon.id, company.id, battalion.id FROM stormtrooper\n" +
"INNER JOIN squad ON squad.id=stormtrooper.squad\n" +
"INNER JOIN platoon ON platoon.id=squad.platoon\n" +
"INNER JOIN company ON company.id=platoon.company\n" +
"INNER JOIN battalion ON battalion.id=company.battalion;" );
String log = "";
while ( rs.next() ) {
log+=rs.getInt("id") + " | ";
log+=rs.getInt("id") + " | ";
log+=rs.getInt("id") + " | ";
log+=rs.getInt("id") + " | ";
log+=rs.getInt("id") + "\n";
}
jTextArea1.setText(log);
rs.close();
stmt.close();
c.close();
} catch ( Exception e ) {
jTextArea1.setText( e.getClass().getName() + ": " + e.getMessage() );
}
SELECT statement is correct - I checked this. But when I try execute this in Java, I'm getting an error:
ambiguous column: 'id'
How should it looks like?

You have a lot of id columns in your SELECT statement
You have to change the columns names with some like this:
SELECT stormtrooper.id AS stormtrooper_id, squad.id AS squad_id, platoon.id AS platoon_id, company.id AS company_id, battalion.id AS battalion_id FROM ...

Related

Why I keep getting the error : org.postgresql.util.PSQLException: ERROR: syntax error at or near "(" in my jdbc code?

I am trying to write a method in jdbc in order to update some columns in my database (postgresql)
Here is what I have written so far:`
public void showRoomBookings(int clientID) {
Scanner myObj = new Scanner(System.in);
Statement st;
try {
st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet res = st.executeQuery("SELECT rb.\"hotelbookingID\",rb.\"roomID\",rb.\"bookedforpersonID\",rb.checkin,rb.checkout,rb.rate\r\n"
+ "FROM roombooking rb ,hotelbooking hb\r\n"
+ "where rb.\"bookedforpersonID\"=hb.\"bookedbyclientID\"\r\n"
+ "AND hb.\"bookedbyclientID\"="+clientID+"\r\n"
+ "order by rb.\"hotelbookingID\"");
int j=1;
while(res.next()) {
System.out.println(j+")roomID:"+res.getInt(2)
+" bookedforpersonID:"+res.getInt(3)+" checkin:"+res.getDate(4)+" checkout:"+res.getDate(5)
+" rate:"+res.getInt(6));
j++;
}
System.out.println("Enter the number of the room you want to update:");
int answer = myObj.nextInt();
ResultSet res1 = st.executeQuery("Select t2.\"hotelbookingID\",t2.\"roomID\",t2.\"bookedforpersonID\",t2.checkin,t2.checkout,t2.rate\r\n"
+ "From \r\n"
+ "(\r\n"
+ " Select \r\n"
+ " Row_Number() Over (Order By t1.\"hotelbookingID\") As RowNum\r\n"
+ " , *\r\n"
+ " From (\r\n"
+ "SELECT rb.\"hotelbookingID\",rb.\"roomID\",rb.\"bookedforpersonID\",rb.checkin,rb.checkout,rb.rate\r\n"
+ "FROM roombooking rb ,hotelbooking hb\r\n"
+ "where rb.\"bookedforpersonID\"=hb.\"bookedbyclientID\"\r\n"
+ "AND hb.\"bookedbyclientID\"=107\r\n"
+ "order by rb.\"hotelbookingID\"\r\n"
+ " )t1\r\n"
+ ") t2\r\n"
+ "Where RowNum = "+answer);
System.out.println("You chose room: ("+answer+")");
while(res1.next()) {
System.out.println(res1.getInt(1)+" roomID:"+res1.getInt(2)
+" bookedforpersonID:"+res1.getInt(3)+" checkin:"+res1.getDate(4)+" checkout:"+res1.getDate(5)
+" rate:"+res1.getInt(6));
res1.updateInt("rate", 40);
res1.updateRow();
}
res.close();
res1.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
In the first ResultSet res I just project the roombookings bases on the clientID and then with ResultSet res1 I choose one of them. My console looks like this:
The problem here is that when I try to update rate :
res1.updateInt("rate", 40);
res1.updateRow();
I get the following message:
org.postgresql.util.PSQLException: ERROR: syntax error at or near "("
Position: 8 at
postgresql#42.2.20.jre7/org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2553)
at
postgresql#42.2.20.jre7/org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2285)
at
postgresql#42.2.20.jre7/org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:323)
at
postgresql#42.2.20.jre7/org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:481)
at
postgresql#42.2.20.jre7/org.postgresql.jdbc.PgStatement.execute(PgStatement.java:401)
at
postgresql#42.2.20.jre7/org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:164)
at
postgresql#42.2.20.jre7/org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:130)
at
postgresql#42.2.20.jre7/org.postgresql.jdbc.PgResultSet.updateRow(PgResultSet.java:1445)
at lol.DbApp.showRoomBookingss(DbApp.java:246) at
lol.DbApp.main(DbApp.java:290)
Here is my postgresql final result(the same as the last line from the console above):
EDIT: SQL CODE:
Select
t2."hotelbookingID",
t2."roomID",
t2."bookedforpersonID",
t2.checkin,
t2.checkout,
t2.rate
From(
Select
Row_Number() Over (
Order By
t1."hotelbookingID"
) As RowNum,
*
From
(
SELECT
rb."hotelbookingID",
rb."roomID",
rb."bookedforpersonID",
rb.checkin,
rb.checkout,
rb.rate
FROM
roombooking rb,
hotelbooking hb
WHERE
rb."bookedforpersonID" = hb."bookedbyclientID"
AND hb."bookedbyclientID" = 107
order by
rb."hotelbookingID"
) t1
) t2
Where
RowNum = 3
group by
t2."hotelbookingID",
t2."roomID",
t2."bookedforpersonID",
t2.checkin,
t2.checkout,
t2.rate
Any help would be valuable.

SQLiteException: near "FROM": syntax error multiple Joins

Can anyone see if there is an error in my query here, it's my first attempt at multiple Joins, below is the logcat error. Thanks in advance
android.database.sqlite.SQLiteException: near "FROM": syntax error
(code 1 SQLITE_ERROR[1]): , while compiling: SELECT SUM(A.quantity),
A.ingredient, A.recipe, B.ingredient_type, B.measurement_name, C.id,
D.plan_name, FROM QUANTITY AS A JOIN INGREDIENTS AS B ON A.ingredient
= B.ingredient_name JOIN PLAN_RECIPES AS C ON A.recipe = C.recipe_name JOIN MEAL_PLAN AS D ON C.id = D.plan_recipe GROUP BY A.ingredient
WHERE D.plan_name LIKE ?
Code
public void loadIngredient() {
shopList.clear();
db = (new DatabaseManager(this).getWritableDatabase());
String RECIPE_SEARCH = " SELECT SUM(A.quantity), A.ingredient, A.recipe, B.ingredient_type, B.measurement_name, C.id, D.plan_name, " +
"FROM " + DatabaseManager.TABLE_QUANTITY + " AS A JOIN " + DatabaseManager.TABLE_INGREDIENTS +
" AS B ON A.ingredient = B.ingredient_name" + " JOIN " + DatabaseManager.TABLE_PLAN_RECIPES + " AS C ON A.recipe = C.recipe_name " +
" JOIN " + DatabaseManager.TABLE_MEAL_PLAN + " AS D ON C.id = D.plan_recipe GROUP BY A.ingredient";
String selectQuery = "";
selectQuery = RECIPE_SEARCH + " WHERE D.plan_name LIKE ?";
c = db.rawQuery(selectQuery, new String[]{"%" + search + "%"});
if (c.moveToFirst()) {
do {
Shopping_List shopping_list = new Shopping_List();
shopping_list.setQuantity(c.getDouble(c.getColumnIndex("quantity")));
shopping_list.setIngredient_name(c.getString(c.getColumnIndex("ingredient_name")));
shopping_list.setIngredient_type(c.getString(c.getColumnIndex("ingredient_type")));
shopping_list.setMeasurement_name(c.getString(c.getColumnIndex("measurement_name")));
shopList.add(shopping_list);
} while (c.moveToNext());
c.close();
}
}
There are several problems in your code.
The 1st is a comma that you must remove after D.plan_name inside the variable RECIPE_SEARCH right before the FROM clause.
The 2nd is the WHERE clause that must precede the GROUP BY clause.
The 3d is that you must alias the column SUM(A.quantity) that is returned by your query so you can retrieve it by that alias, say quantity.
The 4th is that there is no column ingredient_name returned by your query, but I assume this is the column A.ingredient which should be aliased to ingredient_name.
So change to this:
public void loadIngredient() {
shopList.clear();
db = (new DatabaseManager(this).getWritableDatabase());
String RECIPE_SEARCH =
"SELECT SUM(A.quantity) quantity, A.ingredient ingredient_name, A.recipe, B.ingredient_type, B.measurement_name, C.id, D.plan_name " +
"FROM " + DatabaseManager.TABLE_QUANTITY + " AS A JOIN " + DatabaseManager.TABLE_INGREDIENTS + " AS B ON A.ingredient = B.ingredient_name " +
"JOIN " + DatabaseManager.TABLE_PLAN_RECIPES + " AS C ON A.recipe = C.recipe_name " +
"JOIN " + DatabaseManager.TABLE_MEAL_PLAN + " AS D ON C.id = D.plan_recipe " +
"WHERE D.plan_name LIKE ? GROUP BY A.ingredient";
c = db.rawQuery(RECIPE_SEARCH, new String[]{"%" + search + "%"});
if (c.moveToFirst()) {
do {
Shopping_List shopping_list = new Shopping_List();
shopping_list.setQuantity(c.getDouble(c.getColumnIndex("quantity")));
shopping_list.setIngredient_name(c.getString(c.getColumnIndex("ingredient_name")));
shopping_list.setIngredient_type(c.getString(c.getColumnIndex("ingredient_type")));
shopping_list.setMeasurement_name(c.getString(c.getColumnIndex("measurement_name")));
shopList.add(shopping_list);
} while (c.moveToNext());
}
c.close();
db.close();
}
Also, your query returns columns that you don't use in the loop, which I did not remove, by you may remove them.

Oracle Java Prepared Statement Insert if not exists

i have a problem with Java PreparedStatement and Oracle.
In short I want to create a Batch Insert using Java in my Oracle DB. I try to do it with this code:
PreparedStatement preparedStmt = connection.prepareStatement(
"INSERT INTO EFM_BAS_DATA_CLEAN_NUM (date_measured, time_measured, value_reported, data_point_id) " +
" VALUES(?,?,?,?)");
PreparedStatement preparedStmt = connection.prepareStatement(query);
for (EfmBasDataCleanNum measure : measuresToInsert) {
preparedStmt.setString(1, new java.sql.Date(measure.getDateMeasured().getTime()));
preparedStmt.setString(2, measure.getTimeMeasured());
preparedStmt.setDouble(3, measure.getValueReported());
preparedStmt.setInt(4, measure.getDataPointId());
preparedStmt.addBatch();
}
try {
preparedStmt.executeBatch();
}catch (SQLException e){ ...
However when some record already exist in the table, I've this error:
ORA-00001: unique constraint (AFM.UNIQUE_EFM_CLEAN_NUM) violated
cause I've a constraint on this fields.
So, looking on line, I've find many solution.
I tried with this query:
String query = "INSERT INTO EFM_BAS_DATA_CLEAN_NUM (date_measured, time_measured, value_reported, data_point_id) "+
" SELECT TO_DATE(?,'DD/MM/YYYY HH24:MI:SS'),TO_DATE(?,'DD/MM/YYYY HH24:MI:SS'),?,? FROM DUAL "+
" MINUS "+
" SELECT date_measured, time_measured, value_reported, data_point_id FROM efm_bas_data_clean_num";
or with:
String query = " INSERT INTO EFM_BAS_DATA_CLEAN_NUM ( date_measured, time_measured, value_reported, data_point_id ) "
+" SELECT TO_DATE(?, 'DD/MM/YYYY HH24:MI:SS'), TO_DATE(?, 'DD/MM/YYYY HH24:MI:SS'),?,? FROM DUAL "
+" WHERE not exists("
+" SELECT * FROM EFM_BAS_DATA_CLEAN_NUM "
+" WHERE DATE_MEASURED=TO_DATE(?, 'DD/MM/YYYY HH24:MI:SS') "
+" AND TIME_MEASURED=TO_DATE(?, 'DD/MM/YYYY HH24:MI:SS') "
+" AND VALUE_REPORTED=? "
+" AND DATA_POINT_ID=? )";
and finally with:
String query = "MERGE INTO EFM_BAS_DATA_CLEAN_NUM bd1 USING ("
+" SELECT TO_DATE(?, 'DD/MM/YYYY HH24:MI:SS') as DATE_MEASURED, "
+" TO_DATE(?, 'DD/MM/YYYY HH24:MI:SS') as TIME_MEASURED,"
+" ? as VALUE_REPORTED,"
+" ? as DATA_POINT_ID FROM DUAL "
+" ) bd2 on (bd1.DATE_MEASURED=bd2.DATE_MEASURED AND"
+" bd1.TIME_MEASURED=bd2.TIME_MEASURED AND"
+" bd1.VALUE_REPORTED=bd2.VALUE_REPORTED AND"
+" bd1.DATA_POINT_ID=bd2.DATA_POINT_ID)"
+" WHEN NOT MATCHED THEN "
+" INSERT (date_measured, time_measured, value_reported, data_point_id) "
+" VALUES(bd2.DATE_MEASURED,bd2.TIME_MEASURED,bd2.VALUE_REPORTED,bd2.DATA_POINT_ID)";
But while the execution of query in AquaData Studio ever work (or rather when is a new record, it is inserted and when record already exists, it sn't inserted, without errors), on app running, I still have the same error:
ORA-00001: unique constraint (AFM.UNIQUE_EFM_CLEAN_NUM) violated
maybe I'm wrong?
Thanks!
The 'where not exists' version of your code should have worked.
I would double check that you are setting the ? values in your java code correctly, so that your insert values are the same as your 'where not exists' values.
I tried your code with my own tables and it worked. I used select 'X' instead of *, but that shouldn't matter. My sorydct_cert_key is a unique key.
private void testInsert() throws SQLException {
String first = "8ADA";
Integer second = 8;
String third = "ADA Failed";
String fourth = "EXC";
String sql = "INSERT INTO SORYDCT(SORYDCT_CERT_KEY," +
" SORYDCT_CERT_CODE," +
" SORYDCT_CERT_DESC," +
" SORYDCT_PROGRAM," +
" SORYDCT_COUNT_CODE)" +
" SELECT ?,?,?,?, NULL" +
" FROM DUAL" +
" WHERE NOT EXISTS ( SELECT 'X'" +
" FROM SORYDCT" +
" WHERE SORYDCT_CERT_KEY = ?)";
PreparedStatement insertStatement = null;
try {
insertStatement = conn.prepareStatement(sql);
insertStatement.setNString(1, first);
insertStatement.setInt(2, second);
insertStatement.setString(3, third);
insertStatement.setString(4, fourth);
insertStatement.setString(5, first);
insertStatement.executeUpdate();
conn.commit();
} catch (SQLException e) {
System.out.println(ERROR_STRING);
System.out.println("Failure while inserting records - 1");
onException(e);
} finally {
try {
insertStatement.close();
} catch (SQLException e) {
}
}
first = "TEST";
second = 0;
third = "Test";
fourth = "EXC";
System.out.println(sql);
insertStatement = null;
try {
insertStatement = conn.prepareStatement(sql);
insertStatement.setNString(1, first);
insertStatement.setInt(2, second);
insertStatement.setString(3, third);
insertStatement.setString(4, fourth);
insertStatement.setString(5, first);
insertStatement.executeUpdate();
conn.commit();
} catch (SQLException e) {
System.out.println(ERROR_STRING);
System.out.println("Failure while inserting records - 2 ");
onException(e);
} finally {
try {
insertStatement.close();
} catch (SQLException e) {
}
}
} }

Like search not fetching all matching records

I wanted to do multitable search.I have a database in MS Access with 4 tables.So I made 1 more table Index1 which contains the field from all the 4 tables that the user will search.(sort of index/master table). The problem is that the search is not displaying as many records as ideally it should,It displays only few of them. Kindly enlighten me by finding the bug in my code. Thanks in advance !
My code:
//package searchbook;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;
public class SearchBook extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
HttpSession session = request.getSession(true);
List booklist = new ArrayList();
Connection con = null;
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\users\\ppreeti\\executive_db.accdb";
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String user = "";
String pass = "";
String category = "";
category = request.getParameter("input");
String sqlquery = "select Index1.link_id "
+ "FROM Index1 "
+ " WHERE Index1.index_name LIKE '%" + category + "%' ";
String sqlResult = null;
try {
Class.forName(driver);
con = DriverManager.getConnection(url, user, pass);
try {
Statement st = con.createStatement();
System.out.println("Connection created 1");
ResultSet rs = st.executeQuery(sqlquery);
while (rs.next()) {
sqlResult = rs.getString(1);
}
System.out.println("Result retreived 1");
//System.out.println('"sqlquery"');
} catch (SQLException s) {
System.out.println("SQL statement is not executed! " + s);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("************");
String sqlq = "";
int flag = 0;
/*if(sqlResult.equals("1"))
{
flag=1;
System.out.println("entered if block for section!");
sqlq="select Report.Report_Name,Report.Report_ID,Report.Section_ID,Report.Contact_ID,Report.link_id FROM Report "
+ " where Report.Report_Name LIKE '%"+category+"%' ";
sqlq="select Section.Section_Name , Report.Report_Name , Report.Link, Contact.Contact_Name "
+ "FROM Section , Report , Contact"
+ " WHERE Report.Section_ID=Section.Section_ID and Contact.Contact_ID=Report.Report_ID "
+ "and Section.Section_Name = '"+category+"' ";
} */
if (sqlResult.equals("1")) {
flag = 1;
System.out.println("entered if block for section!");
/*sqlq="select Report.Report_Name,Report.Report_ID,Report.Section_ID,Report.Contact_ID,Report.link_id FROM Report "
+ " where Report.Report_Name LIKE '%"+category+"%' ";*/
sqlq = "select distinct Section.Section_Name , Report.Report_Name , Report.Link, Contact.Contact_Name "
+ "FROM Section , Report , Contact"
+ " WHERE Report.Section_ID=Section.Section_ID and Contact.Contact_ID=Report.Contact_ID and Section.Section_Name LIKE '%" + category + "%' ";
// + "and Section.Section_Name = '"+category+"' ";
}
if (sqlResult.equals("2")) {
flag = 1;
System.out.println("entered if block for report!");
/*sqlq="select Report.Report_Name,Report.Report_ID,Report.Section_ID,Report.Contact_ID,Report.link_id FROM Report "
+ " where Report.Report_Name LIKE '%"+category+"%' ";*/
sqlq = "select distinct Section.Section_Name , Report.Report_Name , Report.Link, Contact.Contact_Name "
+ "FROM Section , Report , Contact"
+ " WHERE Report.Section_ID=Section.Section_ID and Contact.Contact_ID=Report.Contact_ID and Report.Report_Name LIKE '%" + category + "%' ";
// + "and Report.Report_Name = '"+category+"' ";
}
if (sqlResult.equals("3")) {
flag = 1;
System.out.println("entered if block for metrics !");
/*sqlq="select Report.Report_Name,Report.Report_ID,Report.Section_ID,Report.Contact_ID,Report.link_id FROM Report "
+ " where Report.Report_Name LIKE '%"+category+"%' "*/
;
sqlq = "select distinct Section.Section_Name , Report.Report_Name , Report.Link, Contact.Contact_Name "
+ "FROM Section , Report , Contact,Metrics"
+ " WHERE Report.Section_ID=Section.Section_ID and Contact.Contact_ID=Report.Contact_ID and Metrics.Report_ID=Report.Report_ID "
+ "and Metrics.Metric_Name LIKE '%" + category + "%' ";
}
if (sqlResult.equals("4")) {
flag = 1;
System.out.println("entered if block for contact name!");
/*sqlq="select Section.Section_Name , Report.Report_Name , Report.Link, Contact.Contact_Name, Metrics.Metric_Name "
+ "FROM Section , Report , Contact, Metrics"
+ " WHERE Report.Section_ID=Section.Section_ID and Metrics.Report_ID=Report.Report_ID "
+ "and Report.Report_ID IN (SELECT Report.Report_ID FROM Report WHERE "
+ "Contact.Contact_ID=Report.Contact_ID and Contact.Contact_Name LIKE '%"+category+"%' and Metrics.Metric_Segment = 'M') ORDER BY Report_Name ";*/
sqlq = "select distinct Section.Section_Name , Report.Report_Name , Report.Link, Contact.Contact_Name "
+ "FROM Section , Report , Contact"
+ " WHERE Report.Section_ID=Section.Section_ID and Contact.Contact_ID=Report.Contact_ID "
+ "and Contact.Contact_Name LIKE '%" + category + "%' ";
}
if (flag == 1) {
try {
Class.forName(driver);
con = DriverManager.getConnection(url, user, pass);
try {
Statement st = con.createStatement();
System.out.println("Connection created");
ResultSet rs = st.executeQuery(sqlq);
System.out.println("Result retreived for 2nd query ");
while (rs.next()) {
List<String> book = new ArrayList<String>();
String Name = rs.getString("Section_Name");
String reportName = rs.getString("Report_Name");
String link = rs.getString("Link");
String contactName = rs.getString("Contact_Name");
/* String metricName=rs.getString("Metric_Name");*/
//String reportId=rs.getString("Report_ID");
book.add(Name);
book.add(reportName);
book.add(link);
book.add(contactName);
/* book.add(metricName);*/
//book.add(reportId);
/* book.add(ind_id);
book.add(ind_name);*/
booklist.add(book);
}
} catch (SQLException s) {
s.printStackTrace();
System.out.println("SQL statement is not executed in 2nd query! " + s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("And it came here lastly !");
request.setAttribute("booklist", booklist);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/searchbook.jsp");
dispatcher.forward(request, response);
System.out.println("***************************************************************************************");
}
}
Check your logic again. In this loop
while (rs.next()) {
sqlResult = rs.getString(1);
}
you are looping through the first ResultSet, repeatedly assigning
sqlResult = rs.getString(1);
and then doing nothing with it until you hit the end of that while loop, after which you proceed to do some other stuff with the last row fetched by that first query.
Access works different. Use "*" instead of "%" for the like.

GAE query working for unit testing but not local testing

My unit testing working fine for this query, but when i run my app in local it doesn't find the column seller.
String statement = "SELECT * FROM " + TABLE_NAME + " "
+ "INNER JOIN " + DbSeller.TABLE_NAME + " seller ON video.seller = seller.id "
+ "WHERE video.name LIKE ?";
//create statement
PreparedStatement stmt = DataBase.getInstance().prepareStatement(statement);
//set data
stmt.setString(1, "%" + s + "%");
//send query
ResultSet rs = stmt.executeQuery();
//the result
while(rs.next()) {
Video v = new Video();
System.out.println("test === " + rs.getInt("seller.id")); // <---- EXCEPTION (Column not found!!!!)
set(rs, v);
listVideo.add(v);
}
stmt.close();
And if i do this instead, it is fine: (Just for the test i don't want ending up writing column by column which info i need)
String statement = "SELECT video.*, seller.id as seller_id FROM " + TABLE_NAME + " "
+ "INNER JOIN " + DbSeller.TABLE_NAME + " seller ON video.seller = seller.id "
+ "WHERE video.name LIKE ?";
//create statement
PreparedStatement stmt = DataBase.getInstance().prepareStatement(statement);
//set data
stmt.setString(1, "%" + s + "%");
//send query
ResultSet rs = stmt.executeQuery();
//the result
while(rs.next()) {
Video v = new Video();
System.out.println("test === " + rs.getInt("seller_id")); // <---- NO EXCEPTION
set(rs, v);
listVideo.add(v);
}
stmt.close();
Note: My app is running on the same offline database in MySQL, so the only difference is that i run this query through my app instead of the unit testing.
Column names seller_id (underscore) and seller.id (dot) look different to me

Categories