JDBC - Query returns no values - java

I am trying to make a query that returns a simple series of results using JDBC on a java class. The Query only needs 1 join for it to work yet, for some reason, it does not return any values. However, when this query is ran on the Oracle SQL Developer, the correct results are shown. below is the code i am currently using.
To Access Database
query = "select h.house_id, h.house_address, h.house_type, h.status, l.firstname, l.surname, h.price_per_month "
+ "from houses_tbl h join landlord_tbl l on l.landlord_id = h.landlord_id";
conn = connectToDatabase();
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
System.out.println(query);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
To Retrieve Data
response.setContentType("application/json");
fullJsonString = "{";
fullJsonString += "\"houses\":[";
ArrayList<HouseObj> allHouses = new ArrayList<HouseObj>();
try {
while (rs.next()) {
int houseID = rs.getInt(1);
Struct address = (Struct) rs.getObject(2);
Object[] taskAddress = address.getAttributes();
String houseAddressStreet = taskAddress[0].toString();
String houseAddressTown = taskAddress[1].toString();
String houseAddressCounty = taskAddress[2].toString();
String houseAddressCountry = taskAddress[3].toString();
String houseAddressPostcode = taskAddress[4].toString();
String houseFullAddress = houseAddressStreet + ", "
+ houseAddressTown + ", " + houseAddressCounty
+ ", " + houseAddressCountry + ", "
+ houseAddressPostcode;
String type = rs.getString(3);
String status = rs.getString(4);
String landlord = rs.getString(5)+" "+rs.getString(6);
int price = rs.getInt(7);
HouseObj newClient = new HouseObj(houseID,
houseFullAddress, type, status, landlord, price);
allHouses.add(newClient);
}
System.out.println("Number Of Houses : "+allHouses.size());
for (int i = 0; i < allHouses.size(); i++) {
if (i == allHouses.size() - 1) {
fullJsonString += "{\"id\":\""
+ allHouses.get(i).getHouseId() + "\","
+ "\"address\":\""
+ allHouses.get(i).getAddress() + "\","
+ "\"type\":\""
+ allHouses.get(i).getType() + "\","
+ "\"status\":\""
+ allHouses.get(i).getStatus() + "\","
+ "\"landlord\":\""
+ allHouses.get(i).getLandlord() + "\","
+ "\"price\":\""
+ allHouses.get(i).getPrice() + "\"}";
} else {
fullJsonString += "{\"id\":\""
+ allHouses.get(i).getHouseId() + "\","
+ "\"address\":\""
+ allHouses.get(i).getAddress() + "\","
+ "\"type\":\""
+ allHouses.get(i).getType() + "\","
+ "\"status\":\""
+ allHouses.get(i).getStatus() + "\","
+ "\"landlord\":\""
+ allHouses.get(i).getLandlord() + "\","
+ "\"price\":\""
+ allHouses.get(i).getPrice() + "\"},";
}
}
fullJsonString += "]}";
} //Catch Exception Below
Output
Number Of Houses : 0
{"houses":[]}
Any help to resolve this is greatly appreciated.

From your posted code, I don't see any printing of the resultset.
How do you know it's not returning anything?
Can you put a print statement before/after the while (rs.next) cycle (an if, a counter) to see if it' s actually empty?
If it is empty, try removing table alias from your query
EDIT:
Modify the query in "select house_id from houses_tbl", execute the query and exactly after
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
put
if (rs.next()){
System.out.println("Got house!");
}else{
System.out.println("No houses here!");
}
and momentarily comment out/bypass the printing code. This is to check baseline operativity of you env in that context. If this doesn't work, must be a database/driver issue, to me

Related

Java [SQLITE_ERROR] SQL error or missing database (near "resi": syntax error)

i have some issues when i'm run the program. It says "[SQLITE_ERROR] SQL error or missing database (near "resi": syntax error)" and "ada yang salah:java.sql.SQLException: ResultSet is TYPE_FORWARD_ONLY". Am i passed something or what?
connection code
public void koneksiDatabase(){
try{
Class.forName("org.sqlite.JDBC");
con = DriverManager.getConnection("jdbc:sqlite:C:/Users/sqlite3/cekresi.db","root","");
System.out.println("Koneksi berhasil!");
}catch(ClassNotFoundException eclass){
System.out.println("Koneksi Gagal!");
}catch(SQLException esql){
System.out.println(esql.getMessage());
}
}
savedata code
public void simpanData(){
try {
String sql = "Insert into data resi = \"" + txtResi.getText() + "\","
+ "nama = \"" + txtNama.getText() + "\","
+ "tujuan = \"" + (String)cmbTujuan.getSelectedItem() + "\","
+ "tarif = \"" + txtTarif.getText() + "\","
+ "berat = \"" + txtBerat.getText() + "\","
+ "jumlah = \"" + txtJumlah.getText() + "\"";
Statement stmt = con.createStatement();
stmt.executeUpdate(sql);
System.out.println("berhasil!");
}catch (Exception e){
System.out.println(e);
}
tampilDataKeTabel();
}
showtable code
public void tampilDataKeTabel(){
ResultSet rs = null;
try{
Statement stmt = con.createStatement();
rs = stmt.executeQuery("select * from data");
ResultSetMetaData meta = rs.getMetaData();
int col = meta.getColumnCount();
int baris = 0;
while (rs.next()){
baris = rs.getRow();
}
dataTable = new String[baris][col];
int x = 0;
rs.beforeFirst();
while(rs.next()){
dataTable[x][0] = rs.getString("resi");
dataTable[x][1] = rs.getString("nama");
dataTable[x][2] = rs.getString("tujuan");
dataTable[x][3] = rs.getString("tarif");
dataTable[x][4] = rs.getString("berat");
dataTable[x][5] = rs.getString("jumlah");
x++;
}
tabelDisplay.setModel(new DefaultTableModel(dataTable,header));
}catch(Exception e){
System.err.println("ada yang salah:"+e);
}
}
There are syntax issues in the insert statement. The syntax should be:
INSERT INTO table (column1,column2 ,..)
VALUES( value1, value2 ,...);
So your insert statement should be something like:
String sql = "Insert into data(resi,nama,tujuan,tarif,berat,jumlah)
values(\"" + txtResi.getText() + "\","
+ \"" + txtNama.getText() + "\","
+ \"" + (String)cmbTujuan.getSelectedItem() + "\","
+ \"" + txtTarif.getText() + "\","
+ \"" + txtBerat.getText() + "\","
+ \"" + txtJumlah.getText() + "\")";
Also, there is an issue in the code to show the data.
while (rs.next()){
baris = rs.getRow();
}
This loop is traversing the result set once. So the next loop would fail as rs has already reached the end of results.
This is causing the exception : ResultSet is TYPE_FORWARD_ONLY
Instead of creating a 2D string array, Create a class corresponding to your db table and then create a List. Assuming a class named Data would be created, the second while loop would be :
List<Data> dataList = new ArrayList<>();
while(rs.next()){
Data data = new Data();
data.setResi(rs.getString("resi"));
data.setNama(rs.getString("nama"));
data.setTujuan(rs.getString("tujuan"));
data.setTarif(rs.getString("tarif"));
data.setBerat(rs.getString("berat"));
data.setJumlah(rs.getString("jumlah"));
dataList.add(data);
}

Java JDBC MySQL exception: “Operation not allowed after ResultSet closed” with Web Page read [duplicate]

This question already has answers here:
Java JDBC MySQL exception: "Operation not allowed after ResultSet closed"
(2 answers)
Closed 5 years ago.
I am using the MySQL connector to get the URL to find values on the web pages.
I am getting the above message and I am not sure why. It inserts the first record from the rs1, but I am not sure why it is closing it.
Below is my code
String strSQL = "SELECT * FROM element_info;";
String sElementID = "";
String sSymbol = "";
URL urlChartLink;
URLConnection urlconn;
String sChartLink = "";
String sCurrentPrice = "";
String FindValue = "last_last";
try {
Class.forName(driver).newInstance();
Connection mysqlconn = DriverManager.getConnection(url + dbName, userName, password);
Statement st1 = mysqlconn.createStatement();
ResultSet rs1 = st1.executeQuery(strSQL);
while (rs1.next()) {
// Get all of the elements
// Retrieve the ElementID
sElementID = rs1.getString(1);
// Retrieve the Symbol
sSymbol = rs1.getString(2);
// Retrieve the Chartlink
sChartLink = rs1.getString(3);
if (sChartLink == "") {
break;
}
try {
urlChartLink = new URL(sChartLink);
urlconn = urlChartLink.openConnection();
urlconn.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
BufferedReader in = new BufferedReader(new InputStreamReader(urlconn.getInputStream(), "UTF-8"));
String currentLine;
while ((currentLine = in.readLine()) != null) {
// See if the value is on this record
int pos1 = currentLine.indexOf(FindValue);
int pos2 = currentLine.indexOf("</span>");
// pos1 = 66
if (pos1 > 0) {
pos1 = pos1 + 21;
pos2 = pos2 - 1;
// System.out.print("pos1 = " + pos1 + "\n");
// System.out.print("pos2 = " + pos2 + "\n");
sCurrentPrice = currentLine.substring(pos1, pos2);
// System.out.print("sCurrentPrice = " + sCurrentPrice + "\n");
// Import into the marketprices
strSQL = "INSERT INTO marketprices"
+ "(ElementID,Symbol,PullDatetime,Price) VALUES (" + "'" + sElementID + "','"
+ sSymbol + "','" + sToday + "','" + sCurrentPrice + "')";
int val = st1.executeUpdate(strSQL);
if (val == 1)
System.out.print("Successfully inserted from " + sChartLink + "\n");
break;
}
}
in.close();
} catch (IOException e) {
System.out.print("Error getting ChartLink website: " + e.getMessage() + "\n");
break;
}
}
} catch (Exception e) {
System.out.print("Error: " + e.getMessage() + "\n");
e.printStackTrace();
}
You are trying to write with a statement object that is already in use as you are still reading the existing resultset from that statement object. You need to create a new statement object for the update portion of your code:
strSQL = "INSERT INTO marketprices"+ "(ElementID,Symbol,PullDatetime,Price) VALUES (" + "'" + sElementID + "','"+ sSymbol + "','" + sToday + "','" + sCurrentPrice + "')";
Connection mysqlconn2 = DriverManager.getConnection(url + dbName, userName, password);
Statement st2 = mysqlconn.createStatement();
int val = st2.executeUpdate(strSQL);

Try with resource class variable gets null

protected void saveData() {
Map<String, String> allStationsParams = new HashMap<>();
List<String> stations = getAllStations();
stmt = Database.getUpdateableStatement();
today = (SysTime.currentTimeMillis() / DasStamp.TICKS_PER_DAY) *
DasStamp.TICKS_PER_DAY;
String changeTimestamp = DasStamp.asCompactString(today);
String keyName = "COM.MAPPINGTOOLTIP." + attributeValue;
for (int row = 0; row < this.getTableModel().getRowCount(); row++) {
String station = (String)this.getTableModel().getValueAt(row, 0);
putInStationParams(this, station, allStationsParams, row);
}
for (String station : stations) {
boolean sendToDB = false;
try (ResultSet rs = this.rsParameters) {
rs.beforeFirst();
while (rs.next()) {
if (rs.getString("station").equals(station)) {
sendToDB = true;
break;
}
}
if (sendToDB) {
if (!rs.getString("value_text").equals(allStationsParams.get(station)) || !allStationsParams.containsKey(station)) {
sendToDB = true;
} else {
sendToDB = false;
}
} else if (allStationsParams.containsKey(station)) {
sendToDB = true;
}
if (sendToDB) {
String sql = "REPLACE INTO dss_parameter (key_name, station, valid_from, value_text"
+ ", change_timestamp) VALUES ('"
+ keyName + "','" + station + "','" + DasStamp.asDateOnlyString(today) + "','"
+ Helper.nz(allStationsParams.get(station)) + "','"
+ changeTimestamp + "') ;";
if (null != stmt) {
stmt.execute(sql);
if (!isResultSetEmpty(rs) && !rs.isAfterLast()) {
AdminLogger.log("dss_parameter", Action.UPDATE,
"key_name='" + keyName + "' and station='" + station + "' and valid_from='" + DasStamp.asDateOnlyString(today) + "'",
"value_text='" + rs.getString("value_text") + "'",
"value_text='" + Helper.nz(allStationsParams.get(station)) + "', change_timestamp='" + changeTimestamp + "'");
} else {
AdminLogger.log("dss_parameter", Action.INSERT,
"key_name='" + keyName + "' and station='" + station + "' and valid_from='" + DasStamp.asDateOnlyString(today) + "'",
"", "value_text='" + Helper.nz(allStationsParams.get(station)) + "', change_timestamp='" + changeTimestamp + "'");
}
}
}
} catch (SQLException e) {
AppFrame.msgBox("Error on insert: " + e.getMessage());
Helper.printMessage(true, false, "Parameter save failed!!", e);
}
}
}
where rsParameters is class level and is fetched before. After first
iteration, rsParameters values is getting null.Is this a problem with try
with resource block? Please help
where rsParameters is class level and is fetched before. After first
iteration, rsParameters values is getting null.Is this a problem with try
with resource block? Please help
Your rsParameters parameter is of Type Resultset.
In first iteration, after try{} block is complete close() method of rsParameters:ResultSet is called.
This internally makes all the properties of resultSet NUll.
That is the reason for getting Null properties during second iteration.
SEE: http://grepcode.com/file/repo1.maven.org/maven2/mysql/mysql-connector-java/5.1.27/com/mysql/jdbc/ResultSetImpl.java#ResultSetImpl.realClose%28boolean%29

no results were returned by the query

Connection con = null;
Statement stmt = null;
Statement resultStmt = null;
ResultSet rs = null;
try {
// load database driver driver
System.out.println("Database driver is: " + DataSource.getClassName());
Class.forName(DataSource.getClassName());
// connect to database from a given URL with a given username and password
System.out.println("Database URL is: " + DataSource.getURL());
con = DriverManager.getConnection(DataSource.getURL(), DataSource.getUserName(), DataSource.getPassword());
// create an SQL statement object
stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO leadcustomer " + "VALUES(1, 'junwei', 'Li', 'heaven road','test#test.com')");
String SQLStatement = "SELECT * FROM leadcustomer";
System.out.println("Q1 SQL Statement is: " + SQLStatement);
rs = resultStmt.executeQuery(SQLStatement);
while (rs.next()) {
int customerid = rs.getInt("customerid");
String fistname = rs.getString("firstname");
String surname = rs.getString("surname");
String billAddress = rs.getString("billingAddress");
String email = rs.getString("email");
System.out.println("customerid : " + customerid);
System.out.println("firstname : " + fistname);
System.out.println("surname : " + surname);
System.out.println("billingAddress : " + billAddress);
System.out.println("email : " + email);
System.out.println(customerid + " : " + fistname + "--" + surname + "--" + billAddress + ":" + email);
}
con.close();
// extract name from first row and print
} catch (SQLException e) {
// print details of SQL error
// could be multiple errors chained together
System.err.println("Error(s) occurred");
while (e != null) {
System.err.println("SQLException : " + e.getMessage());
System.err.println("SQLState : " + e.getSQLState());
System.err.println("SQLCode : " + e.getErrorCode());
e = e.getNextException();
System.err.println();
}
}
I'm trying to insert data and select the table after inserted. But it returns the error message "no results were returned by the query"
I did use executeUpdate and executeQuery for different SQL statement.
Any suggestion for that?
BTW, the insert action is running successful.
The only thing I want is just to solve out the error and execute the select statement print out the table..
Your resultStmt hasn't been initialized. Add
resultStmt = con.createStatement();
before
rs = resultStmt.executeQuery(SQLStatement);

Java strange variable assignment enquiry

I've come across a weird situation. The code is as below:
public static int add(String trcd, String tlcd, String dept, String doDate,
String doTime, String andConfirm, Teller admin) throws
Exception {
try {
String table1 = "table1";
String table2 = "table2";
String trap = null;
String trtype = null;
String sql = "select * from " + table2;
DataSet dataset = DBOper.DBQuery("taUtil", sql);
if (dataset.isEmpty()) {
return -1;
}
else {
HashMap map = dataset.getRow(0);
trap = (String) map.get("aut_ap_code");
trtype = (String) map.get("aut_type_code");
//point 1
sql = "insert into " + table1 + " values("+trtype + "','" + doDate + "','" + doTime + "','N','Y')";
DBOper.DBUpdate("taUtil", sql);
if (andConfirm.equals("Y")) {
//point 2
sql = "select * " + table1 +" where tr_create_date='" + doDate + "' and tr_create_time='" + doTime + "' and tr_stcd='Y'";
//point 3
DataSet dataset2 = DBOper.DBQuery("taUtil", sql);
if (dataset2.isEmpty()) {
return -2;
}
else {
String trNo = null;
HashMap map2 = dataset2.getRow(0);
trNo = (String) map2.get("tr_no");
confirm(admin, trNo, "N");
}
}
return 0;
}
}
catch (Exception e) {
throw e;
}
}
The problem is:
at point 3, it
always prints "insert" ie the previous sql value instead of the latest assignment of "select".
Does anybody knows why is it so ?
Thanks
You have a syntax error in your assignment statement:
sql = "insert into " + table1 + " values(trtype + "','" + doDate + "','" + doTime + "','N','Y')";
Try to replace it with:
sql = "insert into " + table1 + " values(" +trtype + "',' " + doDate + "','" + doTime + "','N','Y')";
I'm not sure how you even managed to compile this...
EDIT: If this syntax error does stop the code from compiling and your IDE (assuming you are using one) executes older version of the class that could not be compiled (has happened to me using Eclipse on occasions), I think it could end up doing something completely unpredictable and possibly explain this odd behavior.

Categories