GAE query working for unit testing but not local testing - java

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

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.

Dynamic pivot in SQL Server database

I'm writing a query where there is pivot table that has to generated. Right now below is my code.
select *
from
(select [case owner], [time taken(minutes)] from StatusTable) as pivotdata
pivot(
sum([time taken(minutes)])
for [CASE OWNER] in
("XXX", "AAA", "BBB")
) as pivoting
But instead of giving the rows in for-in, I need to get this dynamically, I've seen a query here SQL Server dynamic PIVOT query? And modified my query to be
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
SET #cols = STUFF((SELECT distinct ',' + QUOTENAME([case owner])
FROM StatusTable c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'select *
from
(select [case owner], [time taken(minutes)] from StatusTable) as pivotdata
pivot(
sum([time taken(minutes)])
for [CASE OWNER] in
('+#cols+')
) as pivoting'
execute(#query)
And this is working fine, but the problem is that I've to use this query in my JDBC program. And without using execute(#query), it is not running in my SQL Server. Can I make this query similar to the first query, so that I can use the same in my program?
Microsoft's JDBC Driver for SQL Server (mssql-jdbc) supports the execution of an anonymous code block (multiple SQL statements) so we can just execute the same SQL code, including the EXECUTE(...) at the end:
String sql = " "
+ "SET NOCOUNT ON; "
+ "DECLARE #cols AS NVARCHAR(MAX), #query AS NVARCHAR(MAX); "
+ " "
+ "SET #cols = "
+ " STUFF( "
+ " ( "
+ " SELECT distinct ',' + QUOTENAME([case owner]) "
+ " FROM StatusTable c "
+ " FOR XML PATH(''), TYPE "
+ " ).value('.', 'NVARCHAR(MAX)'), "
+ " 1, "
+ " 1, "
+ " ''); "
+ " "
+ "set #query = 'select * "
+ "from "
+ "( "
+ " select [case owner], [time taken(minutes)] from StatusTable "
+ ") as pivotdata "
+ "pivot( "
+ " sum([time taken(minutes)]) for [CASE OWNER] in ('+#cols+') "
+ ") as pivoting'; "
+" "
+ "execute(#query); ";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
// print column headings
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.printf("%5s", rsmd.getColumnLabel(i));
}
System.out.println();
rs.next();
// print column values
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.printf("%5s", rs.getString(i));
}
System.out.println();
/* console output:
AAA BBB XXX
2 13 1
*/

java sqlite - display select

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 ...

ResultSet with variable

Ok so basically I have this code:
resultSet = statement.executeQuery("select * from FEEDBACK.COMMENTS");
writeResultSet(resultSet);
private void writeResultSet(ResultSet resultSet) throws SQLException {
System.out.println("jestem w writeresultset");
// resultSet is initialised before the first data set
while (resultSet.next()) {
// it is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g., resultSet.getSTring(2);
String id = resultSet.getString("id");
String user = resultSet.getString("IMIE");
String website = resultSet.getString("NAZWISKO");
String summary = resultSet.getString("ADRES");
String date = resultSet.getString("EMAIL");
String comment = resultSet.getString("TELEFON");
String opisso = resultSet.getString("OPIS");
JTextField myOutput = new JTextField(1600);
myOutput.setText("id w bazie danych to " + id + " imie to " + user
+ " nazwisko to " + website + " adres to " + summary + " email to "
+ date + " teelefon to " + comment + " opis to " + opisso);
add(myOutput);
}
}
What I want to achieve is this:
resultSet = statement.executeQuery("select * from FEEDBACK.COMMENTS
where NAZWISKO LIKE " variable );
writeResultSet(resultSet);
I want to search by variable which is already defined, however I'm stuck and have no idea how to do it like that.
Use PreparedStatement:
String nazwisko = ...
String query = "select * from FEEDBACK.COMMENTS where NAZWISKO LIKE ?";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, nazwisko);
ResultSet rs = pstmt.execute();
while (resultSet.next()) {
//...
}
In case you need to use a wildcard for your LIKE, choose one of these:
nazwisko = nazwisko + "%";
nazwisko = "%" + nazwisko;
nazwisko = "%" + nazwisko + "%";
up , there are alot weird errors with your code:
like cannot find symbol variable con or incompatible type boolean cannot be converted to resultset.
I have tried this: but there is an error when executing
preparedStatement = connect
.prepareStatement("select * from FEEDBACK.COMMENTS where NAZWISKO= ? ; ");
preparedStatement.setString(1, surname3);
while (resultSet.next()) {
String id = resultSet.getString("i
d");
String user = resultSet.getString("IMIE");
String website = resultSet.getString("NAZWISKO");
String summary = resultSet.getString("ADRES");
String date = resultSet.getString("EMAIL");
String comment = resultSet.getString("TELEFON");
String opisso = resultSet.getString("OPIS");
JTextField myOutput = new JTextField(1600);
myOutput.setText("id w bazie danych to " + id + " imie to " + user + " nazwisko to " + website + " adres to " + summary + " email to " + date + " teelefon to " + comment + " opis to " + opisso);
add(myOutput);
}
error:
the query went fine but , the error appears here "while (resultSet.next())"
SEVERE: null
java.lang.NullPointerException
at jdbcexample.Main.readDataBase(Main.java:416)
at jdbcexample.Main$7.mousePressed(Main.java:346)

DB2 Error SQLCODE=-103, SQLSTATE=42604

I am trying to update a table, but it isn't working and giving this sql error.
//Updating Buy Table
Integer stkbid = Integer.parseInt(request.getParameter("stockBid"));
System.out.println("stock buy id : " + stkbid);
//get buy details
PreparedStatement stmtbuy = conn.prepareStatement(
"SELECT \"StockSymbol\", \"Unit\", \"Price\", \"ClearingFee\", \"StampDuty\", \"BrokerFee\"" +
"FROM SPM.\"StockBuy\" WHERE \"StockBuyId\" = '"+ stkbid + "'");
System.out.println("Got stock buy details");
ResultSet rs=stmtbuy.executeQuery();
rs.next();
//String stkcode = rs.getString("StockSymbol");
Integer stkunit = Integer.parseInt(rs.getString("Unit"));
stkunit -= stock.getStockUnit();
Double stkprice = Double.parseDouble(rs.getString("Price"));
Double stkclear = Double.parseDouble(rs.getString("ClearingFee"));
Double stksd = Double.parseDouble(rs.getString("StampDuty"));
Double stkbfee = Double.parseDouble(rs.getString("BrokerFee"));
Double stkval = stkunit * stkprice;
Double stknv = stkval + stkval * (stkclear + stksd + stkbfee);
System.out.println(stknv);
PreparedStatement stmtbuy1 = conn.prepareStatement(
"UPDATE SPM.\"StockBuy\" SET \"Unit\" = " + stkunit + ", \"Value\" = " + stkval + ", \"NetValue\" = " + stknv +
"WHERE \"StockBuyId\" = "+ stkbid);
You are missing a space in before the WHERE clause, which messed up your stknv.
" WHERE \"StockBuyId\" = "+ stkbid);
I think it's an obligation of any poster to remind you that you should use parametrized query. So I shall do the same.
"Please use parametrized query!"
The query that is works has a quote at the end:
" WHERE \"StockBuyId\" = '"+ stkbid + "'");
The one that fails does not
"WHERE \"StockBuyId\" = "+ stkbid);
That might have something to do with it.

Categories